题解 | #用两个栈实现队列#注意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();
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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