LeetCode solutions by tgic

Implement Stack using Queues

https://leetcode.com/problems/implement-stack-using-queues

Last Update 2015-06-28 07:56:53 +0000 View on Github

Source code Read on Github

 1 class MyStack {
 2 
 3     Queue<Integer> queue = new LinkedList<>();
 4 
 5     // Push element x onto stack.
 6     public void push(int x) {
 7         Queue<Integer> swap = new LinkedList<>();
 8 
 9         swap.add(x);
10 
11         while(!queue.isEmpty()){
12             swap.add(queue.remove());
13         }
14 
15         queue = swap;
16     }
17 
18     // Removes the element on top of the stack.
19     public void pop() {
20         // pop from front
21         queue.remove();
22     }
23 
24     // Get the top element.
25     public int top() {
26         // peek from front
27         return queue.peek();
28     }
29 
30     // Return whether the stack is empty.
31     public boolean empty() {
32         return queue.isEmpty();
33     }
34 }
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