Skip to content

Commit cf5eae3

Browse files
Create 0225-implement-stack-using-queues.java
The solution that is provided in the video https://www.youtube.com/watch?v=rW4vm0-DLYc uses a stack operation to implement the top() method. My java translation has been modified to only use queue operations, using the same algorithm as the pop() method uses.
1 parent e4338a9 commit cf5eae3

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: java/0225-implement-stack-using-queues.java

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class MyStack {
2+
Deque<Integer> q;
3+
public MyStack() {
4+
this.q = new ArrayDeque<>();
5+
}
6+
7+
public void push(int x) {
8+
this.q.addLast(x);
9+
}
10+
11+
public int pop() {
12+
int size = this.q.size();
13+
for(int i = 0; i < size - 1; i++)
14+
this.push(this.q.pollFirst());
15+
return this.q.pollFirst();
16+
}
17+
18+
public int top() {
19+
int size = q.size();
20+
for(int i = 0; i < size - 1; i++)
21+
this.push(this.q.pollFirst());
22+
23+
int res = this.q.peekFirst();
24+
this.push(this.q.pollFirst());
25+
return res;
26+
}
27+
28+
public boolean empty() {
29+
return this.q.size() == 0;
30+
}
31+
}

0 commit comments

Comments
 (0)