2-232

class MyQueue {
    private Stack<Integer> stackPush;
    private Stack<Integer> stackPop;

    /** Initialize your data structure here. */
    public MyQueue() {
        this.stackPush=new Stack<Integer>();
        this.stackPop=new Stack<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        this.stackPush.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(this.stackPush.empty() && this.stackPop.empty()){
            throw new RuntimeException("Queue is empty");
        }else if(this.stackPop.empty()){
            while(!this.stackPush.empty()){
                this.stackPop.push(this.stackPush.pop());
            }
        }
        return this.stackPop.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(this.stackPush.empty() && this.stackPop.empty()){
            throw new RuntimeException("Queue is empty");
        }else if(this.stackPop.empty()){
            while(!this.stackPush.empty()){
                this.stackPop.push(this.stackPush.pop());
            }
        }
        return this.stackPop.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return this.stackPush.isEmpty() && this.stackPop.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();
 */

 

posted @ 2018-09-26 12:57  chan_ai_chao  阅读(131)  评论(0编辑  收藏  举报