-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMuQueue.java
40 lines (37 loc) · 920 Bytes
/
MuQueue.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class MyQueue {
private Stack<Integer> stack;
public MyQueue() {
stack = new Stack();
}
// Push element x to the back of queue.
public void push(int x) {
stack.push(x);
}
// Removes the element from in front of queue.
public void pop() {
Stack<Integer> ans = new Stack();
while(!stack.empty()) {
ans.push(stack.pop());
}
ans.pop();
while(!ans.empty()) {
stack.push(ans.pop());
}
}
// Get the front element.
public int peek() {
Stack<Integer> ans = new Stack();
while(!stack.empty()) {
ans.push(stack.pop());
}
int ret = ans.peek();
while(!ans.empty()) {
stack.push(ans.pop());
}
return ret;
}
// Return whether the queue is empty.
public boolean empty() {
return stack.empty();
}
}