用栈实现队列
主要思路:
- 两个栈一个负责入一个负责出栈
完整代码:
var MyQueue = function() {
this.in=[]
this.out=[]
};
/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.in.push(x)
};
/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(!this.out.length){
while(this.in.length){
this.out.push(this.in.pop())
}
}
return this.out.pop()
};
/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(!this.out.length){
while(this.in.length){
this.out.push(this.in.pop())
}
}
return this.out[this.out.length-1]
};
/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return !this.in.length&&!this.out.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()
*/
用队列实现栈
主要思路:
- 一个队列即可模拟栈
- 但是在出的时候需要另一个队列来做备份
完整代码:
// 使用两个队列实现
/**
* Initialize your data structure here.
*/
var MyStack = function() {
this.queue1 = [];
this.queue2 = [];
};
/**
* Push element x onto stack.
* @param {number} x
* @return {void}
*/
MyStack.prototype.push = function(x) {
this.queue1.push(x);
};
/**
* Removes the element on top of the stack and returns that element.
* @return {number}
*/
MyStack.prototype.pop = function() {
// 减少两个队列交换的次数, 只有当queue1为空时,交换两个队列
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();
};
/**
* Get the top element.
* @return {number}
*/
MyStack.prototype.top = function() {
const x = this.pop();
this.queue1.push(x);
return x;
};
/**
* Returns whether the stack is empty.
* @return {boolean}
*/
MyStack.prototype.empty = function() {
return !this.queue1.length && !this.queue2.length;
};