forked from xiaoningning/java-algorithm-2010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueueByStack.java
More file actions
44 lines (34 loc) · 933 Bytes
/
QueueByStack.java
File metadata and controls
44 lines (34 loc) · 933 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
import java.util.Stack;
/**
* Implement a queue with two stacks.
*/
public class QueueByStack<T> {
private Stack<T> head;
private Stack<T> tail;
public QueueByStack() {
head = new Stack<T>();
tail = new Stack<T>();
}
public void enQueue(T v) {
head.push(v);
}
public T deQueue() {
if (tail.size() == 0) {
while (head.size() > 0) {
tail.push(head.pop());
}
}
if (tail.size() == 0)
throw new RuntimeException("queue is empty.");
return tail.pop();
}
public static void main(String[] args) {
QueueByStack<Integer> queue = new QueueByStack<Integer>();
queue.enQueue(2);
queue.enQueue(5);
queue.enQueue(1);
System.out.println(queue.deQueue());
System.out.println(queue.deQueue());
System.out.println(queue.deQueue());
}
}