题解 | #用两个栈实现队列#注意pop时size会变化

用两个栈实现队列

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


public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        //思路 push之前将 栈2的数据移动到栈1
        if(stack2.size() > 0){
            int size = stack2.size();
            for(int i =0;i < size;i++){
                Integer item = stack2.pop();
                stack1.add(item);
            }
        }
        stack1.add(node);
    }
    
    public int pop() {
       //思路 pop之前将 栈1的数据移动到栈2
        if(stack1.size() > 0){
             int size = stack1.size();
            for(int i =0;i< size;i++){
                Integer item = stack1.pop();
                stack2.add(item);
            }
        }
        return stack2.pop();
    }
}
全部评论

相关推荐

陈逸轩1205:才105 哥们在养生呢
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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