【题目】编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek)
代码实现
public class TwoStacksQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public TwoStacksQueue(){
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
public void add(int newNum){
stackPush.push(newNum);
}
public int poll(){
if (stackPop.isEmpty() && stackPush.isEmpty()) {
System.out.println("queue is empty");
return -1;
}else if(stackPop.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek(){
if (stackPop.isEmpty() && stackPush.isEmpty()) {
System.out.println("queue is empty");
return -1;
}else if(stackPop.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TwoStacksQueue queue = new TwoStacksQueue();
int[] testNum = {4,2,4,6,5,0,1,10};
for(int i:testNum){
queue.add(i);
}
for(int i = 0; i < testNum.length; i++){
System.out.println(queue.peek()+" "+queue.poll());
}
}
}