Skip to content

Commit e78bcb8

Browse files
EASY/src/easy/ImplementQueueUsingStacks.java
1 parent da84213 commit e78bcb8

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package easy;
2+
3+
import java.util.Stack;
4+
5+
public class ImplementQueueUsingStacks {
6+
7+
class MyQueue {
8+
9+
Stack<Integer> input = new Stack();
10+
Stack<Integer> output = new Stack();
11+
12+
// Push element x to the back of queue.
13+
public void push(int x) {
14+
input.push(x);
15+
}
16+
17+
// Removes the element from in front of queue.
18+
public void pop() {
19+
peek();
20+
output.pop();
21+
}
22+
23+
// Get the front element.
24+
public int peek() {
25+
if(output.isEmpty()){
26+
while(!input.isEmpty()){
27+
output.push(input.pop());
28+
}
29+
}
30+
return output.peek();
31+
}
32+
33+
// Return whether the queue is empty.
34+
public boolean empty() {
35+
return input.isEmpty() && output.isEmpty();
36+
}
37+
}
38+
}

0 commit comments

Comments
 (0)