剑指Offer:用2个栈实现队列(java版)

题目描述

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

分析

用stack1专门来装元素,那么直接stack1.pop肯定是不行的,stack2用来出元素。
规则是:只要stack2中有元素就pop,如果stack2为空,则将stack1中所有元素倒进satck2中,就是说,新元素只进stack1,元素出来只从stack2出来。
这样,就能保证每次从stack2中pop出来的元素就是最老的元素了。

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    public void push(int node) {
        stack1.push(node);
    }
    public int pop() {
        if(stack1.empty()&&stack2.empty()){
            throw new RuntimeException("empty");
        }else if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }   
        return stack2.pop();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43165002/article/details/93715742