Skip to content

Commit fbdfc00

Browse files
authored
Update Implement Queue using Stacks.java
1 parent 087654b commit fbdfc00

File tree

1 file changed

+31
-37
lines changed

1 file changed

+31
-37
lines changed

Easy/Implement Queue using Stacks.java

Lines changed: 31 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,40 @@
11
class MyQueue {
2+
3+
private final Stack<Integer> stackOne;
4+
private final Stack<Integer> stackTwo;
25

3-
/** Initialize your data structure here. */
4-
Stack<Integer> stack;
5-
Stack<Integer> revStack;
6-
public MyQueue() {
7-
stack = new Stack<>();
8-
revStack = new Stack<>();
9-
}
10-
11-
/** Push element x to the back of queue. */
12-
public void push(int x) {
13-
stack.push(x);
14-
}
15-
16-
/** Removes the element from in front of queue and returns that element. */
17-
public int pop() {
18-
while (!stack.isEmpty()) {
19-
revStack.push(stack.pop());
6+
public MyQueue() {
7+
this.stackOne = new Stack<>();
8+
this.stackTwo = new Stack<>();
209
}
21-
int num = revStack.pop();
22-
while (!revStack.isEmpty()) {
23-
stack.push(revStack.pop());
10+
11+
public void push(int x) {
12+
this.stackOne.push(x);
2413
}
25-
return num;
26-
}
27-
28-
/** Get the front element. */
29-
public int peek() {
30-
while (!stack.isEmpty()) {
31-
revStack.push(stack.pop());
14+
15+
public int pop() {
16+
exchangeElements(stackOne, stackTwo);
17+
int popped = stackTwo.pop();
18+
exchangeElements(stackTwo, stackOne);
19+
return popped;
3220
}
33-
int num = revStack.peek();
34-
while (!revStack.isEmpty()) {
35-
stack.push(revStack.pop());
21+
22+
public int peek() {
23+
exchangeElements(stackOne, stackTwo);
24+
int peeked = stackTwo.peek();
25+
exchangeElements(stackTwo, stackOne);
26+
return peeked;
27+
}
28+
29+
public boolean empty() {
30+
return stackOne.isEmpty();
31+
}
32+
33+
private void exchangeElements(Stack<Integer> stack1, Stack<Integer> stack2) {
34+
while (!stack1.isEmpty()) {
35+
stack2.push(stack1.pop());
36+
}
3637
}
37-
return num;
38-
}
39-
40-
/** Returns whether the queue is empty. */
41-
public boolean empty() {
42-
return stack.isEmpty();
43-
}
4438
}
4539

4640
/**

0 commit comments

Comments
 (0)