一、队列构造函数
实现的方法:enqueue (入队)、dequeue (出队)、front (获取队列头部元素)、isEmpty(是否为空)、size (队列数量)
function Queue() {
const items=[];
//入队
this.enqueue = function (item) {
items.push(item);
};
//出队
this.dequeue = function () {
return items.shift()
};
//获取队列头部元素
this.front = function () {
return items[0];
};
//判断队列元素是否为空
this.isEmpty = function () {
return items.length === 0;
};
//获取队列元素个数
this.size = function () {
return items.length;
};
}
二、使用2个栈,实现一个队列
function Queue() {
const stackOfGet = new Stack();
const stackOfPut = new Stack();
/**
* 入队
*
*/
this.enqueue = function (item) {
while (0 < stackOfGet.count()) {
stackOfPut.push(stackOfGet.pop());
}
stackOfPut.push(item);
};
/**
* 出队
*
*/
this.dequeue = function () {
while (0 < stackOfPut.count()) {
stackOfGet.push(stackOfPut.pop());
}
return stackOfGet.pop();
};
/**
* 队列项数量
*
*/
this.size = function () {
return stackOfGet.count() + stackOfPut.count();
};
/**
* 查看队首元素
*
*/
this.front = function () {
while (0 < stackOfPut.count()) {
stackOfGet.push(stackOfPut.pop());
}
return stackOfGet.top();
};
/**
* 判断队列是否为空
*
*/
this.isEmpty = function () {
return 0 === this.size();
};
/**
* 清空队列
*
*/
this.clear = function () {
stackOfGet.clear();
stackOfPut.clear();
};