Skip to content

Commit f3af4a0

Browse files
authored
Update Implement Queue using Stacks.java
1 parent 3809df8 commit f3af4a0

File tree

1 file changed

+19
-19
lines changed

1 file changed

+19
-19
lines changed

Easy/Implement Queue using Stacks.java

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
class MyQueue {
2-
3-
private final Stack<Integer> stackOne;
4-
private final Stack<Integer> stackTwo;
2+
3+
private final Stack<Integer> first;
4+
private final Stack<Integer> second;
55

66
public MyQueue() {
7-
this.stackOne = new Stack<>();
8-
this.stackTwo = new Stack<>();
7+
this.first = new Stack<>();
8+
this.second = new Stack<>();
99
}
1010

1111
public void push(int x) {
12-
this.stackOne.push(x);
12+
first.push(x);
1313
}
1414

1515
public int pop() {
16-
exchangeElements(stackOne, stackTwo);
17-
int popped = stackTwo.pop();
18-
exchangeElements(stackTwo, stackOne);
19-
return popped;
16+
move(first, second);
17+
int result = second.pop();
18+
move(second, first);
19+
return result;
2020
}
2121

2222
public int peek() {
23-
exchangeElements(stackOne, stackTwo);
24-
int peeked = stackTwo.peek();
25-
exchangeElements(stackTwo, stackOne);
26-
return peeked;
23+
move(first, second);
24+
int result = second.peek();
25+
move(second, first);
26+
return result;
2727
}
2828

2929
public boolean empty() {
30-
return stackOne.isEmpty();
30+
return first.isEmpty();
3131
}
32-
33-
private void exchangeElements(Stack<Integer> stack1, Stack<Integer> stack2) {
34-
while (!stack1.isEmpty()) {
35-
stack2.push(stack1.pop());
32+
33+
private void move(Stack<Integer> from, Stack<Integer> to) {
34+
while (!from.isEmpty()) {
35+
to.push(from.pop());
3636
}
3737
}
3838
}

0 commit comments

Comments
 (0)