-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathQueueWithTwoStacks.java
More file actions
47 lines (42 loc) · 1.19 KB
/
QueueWithTwoStacks.java
File metadata and controls
47 lines (42 loc) · 1.19 KB
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
package _09;
import java.util.Stack;
public class QueueWithTwoStacks {
/**
* 用两个栈,实现队列的从队尾插入元素 offer() 和从队头抛出元素 poll()
*
* 使用两个栈,in 负责插入,out 负责弹出。
* 如果 out 不为空,直接弹出。
* 如果 out 为空,将 in 的元素依次弹出并存放到 out 中,之后对 out 进行弹出操作。
*/
static class MyQueue<T> {
private Stack<T> in = new Stack<>();
private Stack<T> out = new Stack<>();
public void offer(T data) {
in.push(data);
}
public T poll() {
if (out.empty()) {
while (!in.empty()) {
out.push(in.pop());
}
}
if (!out.empty()) {
return out.pop();
}
return null;
}
}
public static void main(String[] args) {
MyQueue<Integer> myQueue = new MyQueue<>();
System.out.println(myQueue.poll());
myQueue.offer(1);
myQueue.offer(2);
myQueue.offer(3);
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
myQueue.offer(4);
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
System.out.println(myQueue.poll());
}
}