栈和队列

题目:编写一个类,用两个栈实现队列,支持队列的基本操作add()、poll()、peek()。

栈是先进后出,队列是先进先出。用两个栈就可完成队列操作:

  1. 定义两个栈stackPush,stackPop。
  2. 所有数据先入栈stackPush,再出栈stackPush,
  3. 然后入栈stackPop,再出栈stackPop。
  4. 注意:如果stackPop栈不为空,则不能入栈stackPop。
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
import java.util.Stack;
public class {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStackQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
* 添加队尾元素
* @param data 添加的数据
*/
public void add(int data) {
stackPush.push(data);
}
* 删除队首的元素
* @return 为空则返回null
*/
public int poll() {
if (stackPop.empty() && stackPush.empty()) { //如果两个栈都为空,则删除失败
throw new RuntimeException("Queue is empty!");
} else if (stackPop.empty()) { //如果栈2为空,则将栈1的内容全部弹出后压入
stackPop.push(stackPush.pop());
}
return stackPop.pop();
}
* 访问队首元素,与上面的poll()方法相同,返回时不删除而已
* @return
*/
public int peek(){
if (stackPop.empty() && stackPush.empty()) { //如果两个栈都为空,则删除失败
throw new RuntimeException("Queue is empty!");
} else if (stackPop.empty()) { //如果栈2为空,则将栈1的内容全部弹出后压入,弹出栈顶
stackPop.push(stackPush.pop());
}
return stackPop.peek();
}
}