forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyQueue.java
41 lines (34 loc) · 969 Bytes
/
MyQueue.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
41
import java.util.Stack;
/**
* https://leetcode.com/articles/implement-queue-using-stacks/
*/
public class MyQueue {
private Stack<Integer> mStack = new Stack<Integer>();
private Stack<Integer> mStackTmp = new Stack<Integer>();
// Push element x to the back of queue.
public void push(int x) {
mStack.push(x);
}
// Removes the element from in front of queue.
public void pop() {
dump(mStack, mStackTmp);
mStackTmp.pop();
dump(mStackTmp, mStack);
}
// Get the front element.
public int peek() {
dump(mStack, mStackTmp);
int peek = mStackTmp.peek();
dump(mStackTmp, mStack);
return peek;
}
// Return whether the queue is empty.
public boolean empty() {
return mStack.isEmpty();
}
private void dump(Stack<Integer> left, Stack<Integer> right) {
while (!left.isEmpty()) {
right.push(left.pop());
}
}
}