关于队列的介绍可以看之前写的关于栈实现队列的文章
关于链表的介绍可以看之前写的JS反转链表的文章
数组VS链表哪个实现队列更快?
数组是连续存储,push很快,shift很慢
链表是非连续存储,add和delete都很快,查找很慢
性能
空间复杂度都是O(n)
add:链表O(1) 数组O(1)
delete:链表O(1) 数组O(n)
综上:链表实现队列会很快。
链表实现队列
- 单向链表,要同时记录head和tail
- 要从tail入队,从head出队,否则出队时tail不好定位
- length要实时记录,不可遍历链表获取
interface IListNode{
value:number
next:IListNode | null
}
class MyQueue{
private head:IListNode | null=null
private tail:IListNode | null=null
private len = 0
//在tail入队
add(n:number){
const newNode:IListNode={
value:n,
next:null,
}
//处理head
if(this.head==null){
this.head=newNode
}
//处理tail
const tailNode=this.tail
if(tailNode){
tailNode.next=newNode
}
this.tail=newNode
//记录长度
this.len++
}
//在head出队
delete():number | null {
const headNode=this.head
if(headNode==null) return null
if(this.len<=0) return null
//取值
const value =headNode.value
//处理head
this.head=headNode.next
//记录长度
this.len--
return value
}
get length():number{
//length要单独存储,不能遍历链表获取,否则时间复杂度太高
return this.len
}
}