用两个栈实现队列-JS实现
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:
- 用两个栈实现,一个栈实现push的操作,另一个栈实现pop的操作;
- 有元素执行push,则直接push进inStack;
- 当执行pop操作时,需要判断outStack是否为空时;outStack为空时,检查inStack是否为空,若inStack不为空,则可将inStack中的元素pop出,同时push进outStack;outStack不为空则将直接执行pop操作。
//two stacks for in and out
var inStack = [];
var outStack= [];
function push(node)
{
// write code here
inStack.push(node);
}
function pop()
{
// write code here
//whether the stack is empty
if(!outStack.length){//if outStack is empty
while(inStack.length){//there are also elements in the stack
outStack.push(inStack.pop());
}
}
return outStack.pop();//pop the element that I want
}