-
Notifications
You must be signed in to change notification settings - Fork 34
/
Solution.java
64 lines (60 loc) · 1.45 KB
/
Solution.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class MyQueue {
Stack<Integer> left=new Stack<Integer>();
Stack<Integer> right=new Stack<Integer>();
public void push(int x) {
if(right.empty()){
left.push(x);
}else{
right.push(x);
}
}
// Removes the element from in front of queue.
public void pop() {
if(!empty()){
if(right.empty()){
while(!left.empty()){
right.push(left.pop());
}
right.pop();
}else{
while(!right.empty()){
left.push(right.pop());
}
left.pop();
}
f();
}
}
// Get the front element.
public int peek() {
int val=0;
if(right.empty()){
while(!left.empty()){
right.push(left.pop());
}
val=right.peek();
}else{
while(!right.empty()){
left.push(right.pop());
}
val=left.peek();
}
f();
return val;
}
// Return whether the queue is empty.
public boolean empty() {
return left.empty()&&right.empty();
}
public void f(){
if(right.empty()){
while(!left.empty()){
right.push(left.pop());
}
}else{
while(!right.empty()){
left.push(right.pop());
}
}
}
}