forked from christine-1017/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueByTwoStacks.java
More file actions
45 lines (39 loc) · 926 Bytes
/
QueueByTwoStacks.java
File metadata and controls
45 lines (39 loc) · 926 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
package datastructure;
import java.util.Stack;
/**
* Use two stack to implement a queue
* @author wish
*
*/
public class QueueByTwoStacks {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void enqueue(int x){
stack1.push(x);
}
public int dequeue(){
if(!stack2.isEmpty())
return stack2.pop();
else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
if(!stack2.isEmpty())
return stack2.pop();
}
System.out.println("queue is tempty");
return -1;
}
public static void main(String[] args) {
QueueByTwoStacks queue = new QueueByTwoStacks();
queue.enqueue(2);
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(8);
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
System.out.println(queue.dequeue());
}
}