队列(Queue)
先进先出
队列实现
class QueueNode
{
constructor (data)
{
this.data = data
this.next = false
}
getData = () => this.data
setData = data => this.data = data
getNext = () => this.next
setNext = next => this.next = next
}
class Queue
{
constructor ()
{
this.head = false
this.tail = false
}
empty ()
{
return this.head === false
}
push (data)
{
let temp = new QueueNode(data)
if (!this.head)
{
this.head = this.tail = temp
}
else
{
this.tail.setNext(temp)
this.tail = temp
}
}
pop ()
{
if (this.empty()) return false
let data = this.head
this.head = this.head.getNext()
return data.getData()
}
Visit ()
{
let p = this.head
let str = ''
while (p)
{
str += `${p.getData()} `
p = p.getNext()
}
console.log(str)
}
clear ()
{
this.head = this.tail = false
}
}
module.exports = { Queue }
网友评论