LeetCode problem#225
Implement Stack using Queues
Solved in 1 languageJava
Solution
120 lines
1import java.util.Queue;
2import java.util.LinkedList;
3
4// one-queue approach
5// enqueue O(n)
6// dequeue O(1)
7class MyStack {
8 Queue<Integer> queue;
9
10 public MyStack() {
11 queue = new LinkedList<Integer>();
12 }
13
14 public void push(int x) {
15 int currentSize = queue.size();
16 queue.offer(x);
17 // Shift by the previous number of elements
18 for (int i = 0; i < currentSize; i++) {
19 queue.offer(queue.poll());
20 }
21 }
22
23 public int pop() {
24 return queue.poll();
25 }
26
27 public int top() {
28 return queue.peek();
29 }
30
31 public boolean empty() {
32 return queue.isEmpty();
33 }
34}
35
36// enqueue O(1)
37// dequeue O(n)
38// class MyStack {
39// Queue<Integer> queue1;
40// Queue<Integer> queue2;
41
42// public MyStack() {
43// queue1 = new LinkedList<Integer>();
44// queue2 = new LinkedList<Integer>();
45// }
46
47// public void push(int x) {
48// queue1.offer(x);
49// }
50
51// public int pop() {
52// while (queue1.size() > 1) {
53// queue2.offer(queue1.poll());
54// }
55// int popped = queue1.poll();
56// Queue<Integer> temp = queue1;
57// queue1 = queue2;
58// queue2 = temp;
59// return popped;
60// }
61
62// public int top() {
63// while (queue1.size() > 1) {
64// queue2.offer(queue1.poll());
65// }
66// int theTop = queue1.peek();
67// queue2.offer(queue1.poll());
68// Queue<Integer> temp = queue1;
69// queue1 = queue2;
70// queue2 = temp;
71// return theTop;
72// }
73
74// public boolean empty() {
75// return queue1.isEmpty();
76// }
77// }
78
79// enqueue O(n)
80// dequeue O(1)
81// class MyStack {
82// Queue<Integer> queue1;
83// Queue<Integer> queue2;
84
85// public MyStack() {
86// queue1 = new LinkedList<Integer>();
87// queue2 = new LinkedList<Integer>();
88// }
89
90// public void push(int x) {
91// queue2.offer(x);
92// while (!queue1.isEmpty()) {
93// queue2.offer(queue1.poll());
94// }
95// Queue<Integer> temp = queue1;
96// queue1 = queue2;
97// queue2 = temp;
98// }
99
100// public int pop() {
101// return queue1.poll();
102// }
103
104// public int top() {
105// return queue1.peek();
106// }
107
108// public boolean empty() {
109// return queue1.isEmpty();
110// }
111// }
112
113/**
114 * Your MyStack object will be instantiated and called as such:
115 * MyStack obj = new MyStack();
116 * obj.push(x);
117 * int param_2 = obj.pop();
118 * int param_3 = obj.top();
119 * boolean param_4 = obj.empty();
120 */Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.