思路:设计两个栈,一个栈作为压入栈,另一个作为弹出栈。

  • 压入栈向弹出栈压入数据的时候,必须一次性全部压入

  • 如果弹出栈不为空,绝对不能向弹出栈中压入数据

  • 如果两个栈都为空,则队列就为空

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
53
54
55
56
57
58
59
60
61
62
63
64
import java.util.Stack;

public class TwoStackQueue {

private Stack<Integer> stackPush;
private Stack<Integer> stackPop;

public static void main(String[] args) {
TwoStackQueue twoStackQueue = new TwoStackQueue();
twoStackQueue.add(1);
twoStackQueue.add(2);
twoStackQueue.add(3);
twoStackQueue.add(4);
twoStackQueue.add(5);

System.out.println("--"+twoStackQueue.poll());
System.out.println("--"+twoStackQueue.peek());
System.out.println("--" + twoStackQueue.poll());
twoStackQueue.add(7);
twoStackQueue.add(8);
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.peek());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
System.out.println("--" + twoStackQueue.poll());
}

public TwoStackQueue() {
stackPop = new Stack<>();
stackPush = new Stack<>();
}

public void add(int a) {
this.stackPush.push(new Integer(a));
}

public int poll() {
if(this.stackPop.isEmpty() && this.stackPush.isEmpty()) {
throw new RuntimeException("the queue is empty!");
} else if(this.stackPop.isEmpty()) {
while(!this.stackPush.isEmpty()) {
this.stackPop.push(this.stackPush.pop());
}
}
return this.stackPop.pop().intValue();
}

public int peek() {
if (this.stackPop.isEmpty() && this.stackPush.isEmpty()) {
throw new RuntimeException("the queue is empty!");
} else if (this.stackPop.isEmpty()) {
while (!this.stackPush.isEmpty()) {
this.stackPop.push(this.stackPush.pop());
}
}
return this.stackPop.peek().intValue();
}
}