32. Implement Queue using Stacks - Jake blog - Java coding practice log (2017)" /> 32. Implement Queue using Stacks - Jake blog - Java coding practice log (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 top, peek/pop from top, size, and is emptyThe operations 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 Real = new Stack<>(); Stack 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(); */

This siteOriginal articleAll follow "Attribution-NonCommercial-ShareAlike 4.0 License (CC BY-NC-SA 4.0)Please retain the following annotations when sharing or adapting:

Original author:Jake Tao,source:「232. Implement Queue using Stacks」

210
0 0 210

Further Reading

Post a reply

Log inYou can only comment after that.
Share this page
Back to top