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