- 指的是允许同时从队尾与对首两端进行存取操作的队列,操作更加灵活。
- 与js中的数组操作十分相似,只是不允许在数组两端以外的位置进行存取操作。
我们要实现的功能:
- addFront/addBack:添加功能
- removeFront/removeBack:删除功能
- frontTop/backTop:获取对首和队尾的值
基于对象实现
- 队首添加,只需要更新 head 索引值,递减
- 队首移除,只需要更新 head 索引值,递增
- 队尾添加,正常更新 count 即可,递增
- 队尾移除,正常更新 count 即可,递减
class Deque {
constructor () {
this.queue = {}
this.count = 0
this.head = 0
}
// 对首添加
addFront (item) {
this.queue[--this.head] = item
}
// 队尾添加
addBack (item) {
// 注意这里是后加,因为需要先从0的位置添加
// 因为队首添加时,从-1开始了
this.queue[this.count++] = item
}
// 对首移除
removeFront () {
if (this.isEmpty()) {
return
}
const headData = this.queue[this.head]
delete this.queue[this.head++]
return headData
}
// 队尾删除
removeBack () {
if (this.isEmpty()) {
return
}
const backData = this.queue[this.count - 1]
delete this.queue[--this.count]
return backData
}
// 获取对首值
frontTop () {
if (this.isEmpty()) {
return
}
return this.queue[this.head]
}
// 获取对尾值
backTop () {
if (this.isEmpty()) {
return
}
return this.queue[this.count - 1]
}
isEmpty () {
return this.size() === 0
}
size () {
return this.count - this.head
}
}
const deq = new Deque()