forked from christine-1017/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackByTwoQueues_2.java
More file actions
50 lines (44 loc) · 995 Bytes
/
StackByTwoQueues_2.java
File metadata and controls
50 lines (44 loc) · 995 Bytes
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
package datastructure;
import java.util.LinkedList;
import java.util.Queue;
/**
* Use two queues to implement a stack
* Push O(n)
* Pop O(1)
* @author wish
*
*/
public class StackByTwoQueues_2 {
Queue<Integer> queue1 = new LinkedList<Integer>();
Queue<Integer> queue2 = new LinkedList<Integer>();
public void push(int x){
queue2.offer(x);
while(!queue1.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer> temp = null;
temp = queue1;
queue1 = queue2;
queue2 = temp;
}
public int pop(){
if(!queue1.isEmpty())
return queue1.poll();
else{
System.out.println("Stack is empty");
return -1;
}
}
public static void main(String[] args) {
StackByTwoQueues_2 stack = new StackByTwoQueues_2();
stack.push(2);
stack.push(4);
stack.push(5);
stack.push(8);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}