BiruLyu
7/27/2017 - 5:14 PM

232. Implement Queue using Stacks(#).java

//我这里假先push1,2,3,再pop,则st1为空,st2剩下2,3,那我再push4,5那咋办呢,我就先把2,3再push进st1,再push4,5,后面peek或者pop的时候再倒回st2里,
//虽然也accept了但是其实不好,其实没必要倒回st1,就让4,5先存在st1,等st2pop完了之后再把st1倒进st2也不迟倒回
public class MyQueue {
     Stack<Integer> first=new Stack<Integer>();
    Stack<Integer> second=new Stack<Integer>();

    /** Initialize your data structure here. */
    public MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        first.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(second.isEmpty()){
        while(!first.isEmpty()){
            second.push(first.pop());
        }
        }
        return second.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(second.isEmpty()){
        while(!first.isEmpty()){
            second.push(first.pop());
        }
        }
        return second.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return first.isEmpty() && second.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
public class MyQueue {
    
    private Stack<Integer> queue;
    /** Initialize your data structure here. */
    public MyQueue() {
        queue = new Stack<>();   
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        Stack<Integer> temp = new Stack<>();
        while (!queue.isEmpty()) {
            temp.push(queue.pop());
        }
        queue.push(x);
        while (!temp.isEmpty()) {
            queue.push(temp.pop());
        }
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return queue.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return queue.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */