由两个栈组成的队列

来源:互联网 发布:a站软件 编辑:程序博客网 时间:2024/05/21 14:54

题目:

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

package com.guet.codetest;
import java.util.Stack;
public class TwoStacksQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;

public TwoStacksQueue(){
stackPush=new Stack<Integer>();
stackPop=new Stack<Integer>();
}

public void add(int pushInt){
stackPush.push(pushInt);
}

public int poll(){
if (stackPop.empty()&&stackPush.empty()) {
throw new RuntimeException("Queue is empty");
}else if (stackPop.empty()) {
while(!stackPush.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()) {
while(!stackPush.empty()){
stackPop.push(stackPush.pop());
}
}

return stackPop.peek();
}


public static void main(String[] args) {
//int array[]={1,2,3,4,5};
int array[]={1,2};
TwoStacksQueue myQueue=new TwoStacksQueue();
for (int i = 0; i < array.length; i++) {
myQueue.add(array[i]);
}
System.out.println(myQueue.peek());
System.out.println(myQueue.poll());
myQueue.poll();
myQueue.add(4);
//抛出自定义队列空异常
//myQueue.poll();
System.out.println(myQueue.poll());
        
}


}