码迷,mamicode.com
首页 > 其他好文 > 详细

2-232

时间:2018-09-26 13:32:23      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:you   div   structure   ted   called   while   ack   stack   vat   

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();
 */

 

2-232

标签:you   div   structure   ted   called   while   ack   stack   vat   

原文地址:https://www.cnblogs.com/chanaichao/p/9706291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!