队列(Queue)定义
队列是遵守先进先出的原则且是有序的项。一个很生动的例子就是排队干饭,先来的先服务,后来的排队尾。
冷静分析
队列的功能包括以下:
- 向队尾添加新的元素
- 移除队列首项
- 返回队列第一个元素
- 队列是否含有元素
- 队列的长度
代码实现
class Queue {
constructor() {
this.index = 0;
this.outIndex = 0; // 队列首项索引值
this.items = {};
}
add(ele) {
this.items[this.index] = ele
this.index++
}
remove() {
if (this.isEmpty()) {
return undefined
}
const delEle = this.items[this.outIndex]
delete this.items[this.outIndex]
this.outIndex++
}
size() {
return this.index - this.outIndex
}
isEmpty() {
return this.size()
}
clear(){
this.index = 0;
this.outIndex = 0;
this.items = {};
}
}
双端队列(Deque)定义
见名知意,即是允许我们从前后两端添加或者移除元素的特殊队列,遵循的原则是先进先出和先进后出,是栈和队列相结合的一种数据结构。
冷静分析
双端队列的功能包括以下:
- 向双端队列前端添加新的元素
- 向双端队列后端添加新的元素
- 移除双端队列前端首项
- 移除双端队列后端首项
- 返回双端队列首尾第一个元素
- 双端队列是否含有元素
- 双端队列的长度
代码实现
class Deque {
constructor() {
this.count = 0
this.outIndex = 0 // 前端首项索引值
this.items = {}
}
addFront(ele) {
/**向双端队列前端添加元素的三种情况:
* 1-双端队列是空的,向前添加元素和先后添加元素是一样的
* 2-前端元素发生了删除的话,outIndex会++,这时需向前端在添加元素需要outIndex--
* 3-当双端队列拥有元素时
*/
if (this.isEmpty()) {
this.addBack(ele)
} else if (this.outIndex > 0) {
this.outIndex--
this.items[this.outIndex] = ele
} else {
for (let i = this.count; i > 0; i--) {
this.items[i] = this.items[i - 1]
}
this.count++
this.outIndex = 0
this.items[this.outIndex] = ele
}
}
addBack(ele) {
this.items[this.count] = ele
this.count++;
}
removeFront() {
if (this.isEmpty()) {
return undefined
}
const delEle = this.items[this.outIndex]
delete this.items[this.outIndex]
this.outIndex++
}
removeBack() {
if (this.isEmpty()) {
return undefined
}
this.count--
const delEle = this.items[this.count]
delete this.items[this.count]
return delEle
}
peekFront() {
if (this.isEmpty()) {
return undefined
}
return this.items[0]
}
peekBack() {
if (this.isEmpty()) {
return undefined
}
return this.items[Object.keys(this.items).length - 1]
}
size() {
return this.count
}
isEmpty() {
return this.size() == 0
}
}