剑指offer(5)用两个栈实现队列

题目描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

解题代码:

var stack1 = [];
var stack2 = [];
//栈:后进先出;队列:先进先出;用栈1来保存进来的数
function push(node)
{
    // write code here
    stack1.push(node);
}
//模拟出队列:出栈1的数全部放进栈2,第一个出栈2的数即为第一个出队的数,返回它,再将剩下的数全部放入栈1
function pop()
{
    // write code here
    while(stack1.length != 0){
        stack2.push(stack1.pop());
    }
    var result = stack2.pop();
    while(stack2.length != 0){
        stack1.push(stack2.pop());
    }
    return result;
}
原文地址:https://www.cnblogs.com/3yleaves/p/9588871.html