链表实现队列
思路分析
- 根据链表的特点,创建两个变量 head, tail.分别指向链表的头和尾
- 定义len 实时记录链表的长度, 获取队列的长度时返回 len
- 增加的时候从链表队尾增加,只需要将当前队尾的next 指向新增节点,tail 指向新的节点
- 删除的时候从链表头部删除,将head 指向 当前头部节点的 next
代码实现
interface MlinkNode {
value: number
next?: MlinkNode | null
}
class MyQueue {
private head: MlinkNode | null = null;
private tail: MlinkNode | null = null;
private len: number = 0
add (n: number) {
const newLinkNode: MlinkNode = {
value: n,
next: null
}
if (this.head === null) {
this.head = newLinkNode
}
let tailNode = this.tail
if (tailNode) {
tailNode.next = newLinkNode
}
this.tail = newLinkNode
this.len++
}
delete ():number | null {
const headNode = this.head
if (this.len < 1) return null
if (headNode == null) return null
const value = headNode.value
this.head = headNode.next as MlinkNode
this.len--
return value
}
get length(): number {
return this.len
}
}
const q = new MyQueue()
q.add(100)
q.add(300)
q.add(200)
console.info(q.length)
console.log(q.delete())