算法
1. 232 Implement Queue using Stacks
function MyQueue() {
this.stack1 = [];
//入队操作, stack1尾部为队列的尾部
this.stack2 = [];
//出队操作,使用一个数组来翻转元素的顺序
}
MyQueue.prototype.push = function (x) {
this.stack1.push(x);
}
MyQueue.prototype.pop = function () {
//如果stack2中没有元素,那么将stack1中元素翻转顺序填入stack2
if (this.stack2.length === 0) {
while (this.stack1.length !== 0) {
this.stack2.push(this.stack1.pop())
}
}
//数组的pop函数是删除并返回数组最后一位
return this.stack2.pop();
}
MyQueue.prototype.peek = function () {
//如果stack2中没有元素,那么将stack1中元素翻转顺序填入stack2
if (this.stack2.length === 0) {
while (this.stack1.length !== 0) {
this.stack2.push(this.stack1.pop())
}
}
return this.stack2[this.stack2.length - 1]
}
MyQueue.prototype.empty = function () {
return this.stack1.length === 0 && this.stack2.length === 0;
}
2. 225 Implement Stack using Queues
function MyStack() {
this.queue = []
}
MyStack.prototype.push = function(x) {
let size = this.queue.length;
this.queue.push(x);
//当使用单队列时,将队列中除刚加入新元素外的所有元素依次从前端移除,并重新从尾部入列
//这样可以实现栈的后进先出
for (let i = 0; i < size; i++) {
this.queue.push(this.queue.shift());
}
}
MyStack.prototype.pop = function () {
return this.queue.shift();
}
MyStack.prototype.peek = function () {
return this.queue[0];
}
MyStack.prototype.empty = function () {
//检查栈是否为空
return this.queue.length === 0;
}