LeetCode solutions by tgic

Implement Queue using Stacks

https://leetcode.com/problems/implement-queue-using-stacks

Last Update 2015-07-07 13:04:46 +0000 View on Github

Source code Read on Github

 1 class MyQueue {
 2 
 3     // should use Deque<Integer> stack in modern java
 4     Stack<Integer> stack = new Stack<>();
 5 
 6     // Push element x to the back of queue.
 7     public void push(int x) {
 8         Stack<Integer> rev = new Stack<>();
 9 
10         while(!stack.empty()){
11             rev.push(stack.pop());
12         }
13         
14         rev.push(x);
15 
16         while(!rev.empty()){
17             stack.push(rev.pop());
18         }
19     }
20 
21     // Removes the element from in front of queue.
22     public void pop() {
23         stack.pop();
24     }
25 
26     // Get the front element.
27     public int peek() {
28         return stack.peek();
29     }
30 
31     // Return whether the queue is empty.
32     public boolean empty() {
33         return stack.empty();
34     }
35 }
comments powered by Disqus

LeetCode solutions by tgic

  • LeetCode solutions by tgic
  • [email protected]
  • Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
  • tg123
  • tg123/leetcode

LeetCode java solutions by tgic