**两个栈实现队列思路:**添加元素的话直接push到栈1,删除队列头部的话是当栈2为空的时候需要先把栈1的元素全放到栈2,然后栈2在pop即可,当栈1栈2的长度都为空时,返回-1,否则栈2有长度直接pop即可。
var MyQueue = function() {
this.stack1=[];
this.stack2=[];
};
MyQueue.prototype.push = function(x) {
this.stack1.push(x)
};
MyQueue.prototype.pop = function() {
if(this.stack2.length===0){
while(this.stack1.length){
this.stack2.push(this.stack1.pop())
}
return this.stack2.pop()
}
if(this.stack2.length===0){
return null;
}
return this.stack2.pop();
};
MyQueue.prototype.peek = function() {
// const x = this.pop();
// this.stack2.push(x)
// return x
if(!this.stack2.length&&!this.stack1.length){
return null
}
if(this.stack2.length){
return this.stack2[this.stack2.length-1]
}else{
return this.stack1[0]
}
};
MyQueue.prototype.empty = function() {
return !this.stack1.length&&!this.stack2.length
};
**两个队列实现栈思路:**队列1用于直接push数据,当出栈时,队列1将元素全部出队列放至队列2,直到队列1只剩下一个数据时,那么这个就是需要出栈的值,记录当前出栈的值,又将队列2出列全部放到队列1,后续即可进行同样的操作。
var MyStack = function() {
this.queue1=[];
this.queue2=[]
};
MyStack.prototype.push = function(x) {
this.queue1.push(x);
};
MyStack.prototype.pop = function() {
while(this.queue1.length > 1){
this.queue2.push(this.queue1.shift())
}
var ans = this.queue1.shift();
while(this.queue2.length){
this.queue1.push(this.queue2.shift())
}
return ans
};
MyStack.prototype.top = function() {
return this.queue1.slice(-1)[0]//slice(-1)也可
};
MyStack.prototype.empty = function() {
return !this.queue1.length
};
**一个队列实现栈:**将队列以数组的形式,使用push和pop方法即可。
var MyStack = function() {
this.queue=[]
};
MyStack.prototype.push = function(x) {
this.queue.push(x);
};
MyStack.prototype.pop = function() {
return this.queue.pop()
};
MyStack.prototype.top = function() {
if(this.queue.length===0){
return null
}
return this.queue[this.queue.length-1]
};
MyStack.prototype.empty = function() {
return this.queue.length===0
};