用两个栈来实现队列
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
时间限制:1秒 空间限制:32768K
思路
两个stack,push函数直接使用instack;pop时,考虑outstack是否为空,不为空,直接pop,为空,将instack全部push进outstack
代码
var inStack = [];
var outStack = [];
function push(node)
{
// write code here
inStack.push(node);
}
function pop()
{
// write code here
if(outStack.length == 0){
if(inStack.length == 0){
return null;
}else{
outStack = [];
while(inStack.length != 0) {
outStack.push(inStack.pop());
}
}
return outStack.pop();
}else {
return outStack.pop();
}
}
运行时间:21ms
占用内存: 5240k
最佳代码
var stack1 = [];
function push(node)
{
// write code here
stack1.push(node);
}
function pop()
{
// write code here
if(stack1.length == 0)
return false;
return stack1.shift();
}
- 直接使用shift()函数