队列的概念
- 队列是一种遵从先进先出原则的有序集合
-
队列的实现
enQueue() 入队方法
- deQueue() 出队方法
- top() 获取队首值
- size() 获取队列长度
clear() 清空队列 ```javascript class Queue { constructor() { this.queue = [] this.count = 0 } // 入队方法 enQueue(item) { this.queue.push(item) this.count++ }
// 出队方法 deQueue() { if (this.isEmpty()) {
return
} this.count— return this.queue.shift(); }
// 是否为空 isEmpty() { return this.count === 0 }
// 获取队首元素值 top() { return this.queue[0] }
size() { return this.count }
// 清空队列 clear() { this.queue = [] this.count = 0 } }
const m = new Queue();
```javascript
class Queue {
constructor() {
this.queue = {}
this.count = 0
// 用于记录队首的键
this.head = 0
}
// 入队方法
enQueue(item) {
this.queue[this.count++] = item
}
// 出队方法
deQueue() {
if (this.isEmpty()) {
return
}
const topValue = this.queue[this.head];
delete this.queue[this.head]
this.head++
this.count--
return topValue
}
// 是否为空
isEmpty() {
return this.count === 0
}
// 获取队首元素值
top() {
return this.queue[this.head]
}
size() {
return this.count
}
// 清空队列
clear() {
this.queue = {}
this.count = 0
this.head = 0
}
}
const m = new Queue();
双端队列
双端队列 指的是允许同时从队尾与队首两端进行存取操作的队列,操作更加灵活
双端队列与 JavaScript 中的数组操作十分相似, 只是不允许在数组两端以外的位置进行存取操作
- addFront/addBack
- removeFront/removeBack
frontTop/backTop
```javascript class Queue { constructor() { this.queue = {} this.count = 0 // 用于记录队首的键 this.head = 0 } // 队首添加 addFront(item) { this.queue[—this.head] = item }// 队尾添加 addBack(item) { this.queue[this.count++] = item }
// 队首删除 removeFront() { if(this.isEmpty()) {
return
} const headValue = this.queue[this.head] delete this.queue[this.head++] return headValue }
// 队尾删除 removeBack() { if(this.isEmpty()) {
return
} const backValue = this.queue[this.count - 1] delete this.queue[—this.count] return backValue }
// 获取队首值 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 }
// 清空队列 clear() { this.queue = {} this.count = 0 this.head = 0 } }