天天看點

用兩個棧實作隊列

用兩個棧來實作一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。

隊列嘛,先進先出,棧嘛,先進後出。 于是乎,把第一個棧扔滿,然後再一一放到另一個棧中,然後再一一取出來。 沒了- -

public class reconstructionQueue {
    
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node){
        stack1.push(new Integer(node));
    }
    
    public int pop(){
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop().intValue();
    }
}      

繼續閱讀