什么是队列
队列(queue):一种特殊的线性表。特殊之处在于它只允许在队列前端进行删除操作,在队列尾部进行添加操作。
- 进行删除的一端称为队头。
- 进行添加的一端称为队尾。
- 队列的特点:先进先出,后进后出。
如下图:
队列常见的操作
- enQueue(item) 在队尾的位置为队列添加一个新的数据
- deQueue() 在队头的位置删除队列的第一个元素
- front() 返回队列的首项
- isEmpty() 判断队列是否为空
- size() 返回队列数据的大小
- toString() 以字符串的形式输出队列中的数据
ES6 实现队列数据结构
这里使用数组实现队列结构,我们约定数组的头部为队头,尾部为队尾。
- 队列结构封装
/**
* 队列结构
* 特点:先进先出,在前端进行删除操作,在后端进行添加操作
*
* @class Queue
*/
class Queue {
constructor() {
this.queue = [];
}
}
- enQueue(item) 方法的实现
// 1. 进入队列
enQueue(item) {
this.queue.push(item);
}
- deQueue() 方法的实现
// 2. 移除队列的首项
deQueue() {
this.queue.shift();
}
- front() 方法的实现
// 3. 查看队列的首项
front() {
return this.queue[0];
}
- isEmpty() 方法的实现
// 4. 队列是否为空
isEmpty() {
return this.queue.length === 0;
}
- size() 方法的实现
// 5. 队列的大小
size() {
return this.queue.length;
}
- toString() 方法的实现
// 6. toString
toString() {
return this.queue.join(" ");
}
队列的总体代码
/**
* 队列结构
* 特点:先进先出,在前端进行删除操作,在后端进行添加操作
*
* @class Queue
*/
class Queue {
constructor() {
this.queue = [];
}
// 队列相关的操作
// 1. 进入队列
enQueue(item) {
this.queue.push(item);
}
// 2. 移除队列的首项
deQueue() {
this.queue.shift();
}
// 3. 查看队列的首项
front() {
return this.queue[0];
}
// 4. 队列是否为空
isEmpty() {
return this.queue.length === 0;
}
// 5. 队列的大小
size() {
return this.queue.length;
}
// 6. toString
toString() {
return this.queue.join(" ");
}
}