用两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路
一个队列包含两个栈,操作两个先进后出的栈实现一个先进先出的队列。在入队的时候,直接压入栈1。出队时,先判断栈2是否为空,如果为空,就把栈1里已经有的元素pop出去,再push进栈2中;如果栈2不为空,先把栈2中的元素pop出去,再把栈1的元素push进来。
代码
function Stack(){
var item = [];
this.push = function(node){
item.push(node);
};
this.pop = function(){
return item.pop();
};
this.isnull = function(){
return item.length===0;
}
}
var stack1 = new Stack();
var stack2 = new Stack();
function push(node)
{
// write code here
stack1.push(node);
}
function pop()
{
// write code here
if(stack1.isnull()&&stack2.isnull()){
return false;
}else if(stack2