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

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。