题目描述:
用两个栈来实现一个队列,完成队列的add和poll、peek操作。
队列中的元素为int类型。
import java.util.Stack;
public class TwoStacksQueue {
public static void main(String[] args) {
TwoStacksQueue mQueue = new TwoStacksQueue(new Stack<Integer>(), new Stack<Integer>());
for(int i = 0; i < 10; i++) {
mQueue.add(i);
}
for(int i = 0; i < 10; i++) {
System.out.println(mQueue.peek());
System.out.println(mQueue.poll());
}
}
private Stack<Integer> pushStack;
private Stack<Integer> popStack;
public TwoStacksQueue(Stack<Integer> pushStack,Stack<Integer> popStack) {
this.pushStack = pushStack;
this.popStack = popStack;
}
public void add(int num) {
pushStack.push(num);
}
public int poll() {
if(pushStack.isEmpty()&&popStack.isEmpty()){
throw new RuntimeException("The queue is empty");
}else if(popStack.isEmpty()) {
while(!pushStack.isEmpty()) {
popStack.add(pushStack.pop());
}
}
return popStack.pop();
}
public int peek() {
if(pushStack.isEmpty()&&popStack.isEmpty()){
throw new RuntimeException("The queue is empty");
}else if(popStack.isEmpty()) {
while(!pushStack.isEmpty()) {
popStack.add(pushStack.pop());
}
}
return popStack.peek();
}
}