题目:编写一个类,用两个栈实现队列,支持队列的基本操作add()、poll()、peek()。
栈是先进后出,队列是先进先出。用两个栈就可完成队列操作:
- 定义两个栈stackPush,stackPop。
- 所有数据先入栈stackPush,再出栈stackPush,
- 然后入栈stackPop,再出栈stackPop。
- 注意:如果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>(); } public void add(int data) { stackPush.push(data); } public int poll() { if (stackPop.empty() && stackPush.empty()) { throw new RuntimeException("Queue is empty!"); } else if (stackPop.empty()) { stackPop.push(stackPush.pop()); } return stackPop.pop(); } public int peek(){ if (stackPop.empty() && stackPush.empty()) { throw new RuntimeException("Queue is empty!"); } else if (stackPop.empty()) { stackPop.push(stackPush.pop()); } return stackPop.peek(); } }
|
近期评论