forked from Jensenczx/CodeEveryday
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path33_QueueByStack.java
43 lines (39 loc) · 991 Bytes
/
33_QueueByStack.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
public class Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Queue() {
// do initialization if necessary
stack1 = new Stack<Integer>;
stack2 = new Stack<Integer>;
}
public void push(int element) {
// write your code here
stack1.push(element);
}
public int pop() {
// write your code here
if(stack2.empty()){
if(stack1.empty())
return 0;
else{
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
}
return stack2.pop();
}
public int top() {
// write your code here
if(stack2.empty()){
if(stack1.empty())
return 0;
else{
while(!stack1.empty()){
stack2.push(stack1.pop());
}
}
}
return stack2.peek();
}
}