JavaScript算法笔记——用两个栈实现队列
题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型。
代码如下:
const inStack=[];
const outStack =[];
function push(node)
{
// write code here
inStack.push(node);
}
function pop()
{
// write code here
if(outStack.length){
return outStack.pop();
}else{
while(inStack.length){
outStack.push(inStack.pop());
}
return outStack.pop();
}
}
原理可查看程序员爱酸奶的博客。