栈是先进后出,队列是先进先出
一、用栈实现队列
问题要点
栈来模拟队列,需要用到两个栈,输入栈和输出栈,输入的话,往输入栈 push 即可,输出的情况需要判断,如果输出栈有值,则直接 pop,否则,把输入栈的元素全部放到输出栈,然后对输出栈 pop
var MyQueue = function () {
this.stackIn = [];
this.stackOut = [];
};
/**
* 将元素放入队列尾部
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function (x) {
this.stackIn.push(x);
};
/**
* 将队列首部移除
* @return {number}
*/
MyQueue.prototype.pop = function () {
let size = this.stackOut.length;
if (size) {
return this.stackOut.pop();
}
while (this.stackIn.length) {
this.stackOut.push(this.stackIn.pop());
}
return this.stackOut.pop();
};
/**
* 队首元素
* @return {number}
*/
MyQueue.prototype.peek = function () {
let val = this.pop();
this.stackOut.push(val);
return val;
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function () {
return !this.stackIn.length && !this.stackOut.length;
};
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
二、用队列实现栈
两个队列实现栈
其中第二个队列是备份的作用
var MyStack = function () {
this.queue1 = [];
this.queue2 = [];
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function (x) {
this.queue1.push(x);
};
/**
* @return {number}
*/
MyStack.prototype.pop = function () {
if (!this.queue1.length) {
[this.queue1, this.queue2] = [this.queue2, this.queue1];
}
while (this.queue1.length > 1) {
this.queue2.push(this.queue1.shift());
}
return this.queue1.shift();
};
/**
* @return {number}
*/
MyStack.prototype.top = function () {
let res = this.pop();
this.queue1.push(res);
return res;
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function () {
return !this.queue1.length && !this.queue2.length;
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
使用一个队列实现
要注意遍历队列的时候留下最后一个,就是需要的栈顶元素
var MyStack = function() {
this.queue = []
};
/**
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue.push(x)
};
/**
* @return {number}
*/
MyStack.prototype.pop = function() {
let size = this.queue.length
while(size-- > 1) {
this.queue.push(this.queue.shift())
}
return this.queue.shift()
};
/**
* @return {number}
*/
MyStack.prototype.top = function() {
let res = this.pop()
this.queue.push(res)
return res
};
/**
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue.length
};
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/