题解 | #用两个栈实现队列#

用两个栈实现队列

http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

队列特性:先进先出

栈特性:先进后出

import java.util.Stack;

/*
队列:先进先出
栈:先进后出
*/
public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();    //栈1--push
    Stack<Integer> stack2 = new Stack<Integer>();    //栈2--pop
    
    public void push(int node) {
        while(!stack2.isEmpty()){    //每次push前先将栈2清空放入栈1(保证先进的在栈2底)
            stack1.push(stack2.pop());
        }
        stack1.push(node);    //元素进栈
    }
    
    public int pop() {
        while(!stack1.isEmpty()){    //每次pop前先将栈1清空放入栈2(保证后进的在栈1底)
            stack2.push(stack1.pop());
        }
        return stack2.pop();
    }
}
全部评论

相关推荐

下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务