JavaScript实现队列
- 队列数据结构
- 创建队列
- 向队列添加元素
- 从队列移除元素
- 查看队列头元素
- 查看队列是否为空
- 打印队列元素
1. 队列数据结构
栈是一种遵从先进先出(FIFO)原则的一组有序的项。队列在尾部添加新元素,并从头部移除元素。最新添加的元素必须排在队列的末尾。
2. 创建队列
创建一个类来表示栈。
function Queue() {
let items = [];
}
3. 向队列添加元素
实现一个push方法
this.enqueue = function(element){
items.push(element);
};
4. 从队列移除元素
this.dequeue = function() {
return items.shift():
};
5. 查看队列头元素
this.front = function() {
return items[0];
};
6. 检查队列是否为空
this.isEmpty = function() {
return items.length === 0;
};
// 返回栈的length
this.size = function() {
return items.length;
};
7. 打印队列元素
this.print= function() {
console.log(items.toString());
};
完整代码
function Queue() {
let items = [];
this.push = function(element){
items.push(element);
};
this.enqueue = function(element){
items.push(element);
};
this.dequeue = function() {
return items.shift():
};
this.front = function() {
return items[0];
};
this.isEmpty = function() {
return items.length === 0;
};
// 返回栈的length
this.size = function() {
return items.length;
};
this.print= function() {
console.log(items.toString());
};
};