您的位置 首页 JAVA(2017)

232. Implement Queue using Stacks

Implement the following operations of a queue using stacks.

  • push(x) — Push element x to the back of queue.
  • pop() — Removes the element from in front of queue.
  • peek() — Get the front element.
  • empty() — Return whether the queue is empty.

Notes:

  • You must use only standard operations of a stack — which means only push to toppeek/pop from topsize, and is emptyoperations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
class MyQueue {

    Stack<Integer> Real = new Stack<>();
    Stack<Integer> NoReal = new Stack<>();
    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        Real.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(Real.empty()){
            return -1;
        }
        while(!Real.empty()){
            NoReal.push(Real.pop());
        }
        int res = NoReal.pop();
        while(!NoReal.empty()){
            Real.push(NoReal.pop());
        }        
        return res;
    }
    
    /** Get the front element. */
    public int peek() {
        if(Real.empty()){
            return -1;
        }
        while(!Real.empty()){
            NoReal.push(Real.pop());
        }
        int res = NoReal.peek();
        while(!NoReal.empty()){
            Real.push(NoReal.pop());
        }        
        return res;
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return Real.empty();
    }
}

/**
 * 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();
 */
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《232. Implement Queue using Stacks》

发表评论

邮箱地址不会被公开。

返回顶部