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

用两个栈实现队列

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

两个栈里面,stack1用于获取元素并存入栈中;stack2在pop()方法中和stack1共同使用:首先将stack1里面的所有元素依次弹出并压入stack2,这样stack2栈顶的元素即是“最先进入队列的元素”,弹出stack2的栈顶元素之后,stack2的元素依次弹出,存回stack1。

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);    //压入stack1
    }
    
    public int pop() {
        //元素出stack1进stack2实现先入先出
        while (stack1.size()!=0) {
            stack2.push(stack1.pop());
        }
        int top = stack2.pop();    //弹出元素赋给top
        //剩余元素存回stack1
        while (stack2.size()!=0) {
            stack1.push(stack2.pop());
        }
        return top;
    }
}

全部评论

相关推荐

zYvv:双一流加大加粗再标红,然后广投。主要是获奖荣誉不够,建议开始不用追求大厂,去别的厂子刷下实习。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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