Skip to main content

用栈实现队列

class QueueByStack {
constructor() {
// 用数组模拟栈,需要两个栈
this.s1 = []; // 第一个栈只用来入队列
this.s2 = []; // 第二个栈只用来出队列
this.enquequ = this.enquequ.bind(this);
this.dequequ = this.dequequ.bind(this);
}
// 入队
enquequ(item) {
this.s1.push(item) // 入队操作:将元素压入第一个栈
}
// 出队
dequequ() {
// 出队列的时候,从第二个栈中出,如果第二个栈中有元素直接pop()出来,如果没有则先将第一个栈的元素全部压入第二个栈中再从第二个栈中出
if (this.s2.length) {
return this.s2.pop();
} else {
while (this.s1.length) {
this.s2.push(this.s1.pop())
}
return this.s2.pop();
}
}
}