【题目】
编写一个类,用两个栈实现队列,支持队列的基本操作(add、poll、peek)。
package leif.algorithm_and_data_structure.stack_and_queue;
import java.util.Stack;
public class TwoStacksQueue {
private Stack<Integer> stackPush = new Stack<Integer>();
private Stack<Integer> stackPop = new Stack<Integer>();
public void add(int pushInt) {
stackPush.push(pushInt);
}
public int poll() {
if (stackPop.isEmpty() && stackPush.isEmpty()) {
throw new RuntimeException("Queue is empty!");
} else if (stackPop.isEmpty()) {
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek() {
if (stackPop.isEmpty() && stackPush.isEmpty()) {
throw new RuntimeException("Queue is empty!");
} else if (stackPop.isEmpty()) {
while (!stackPush.isEmpty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}