程序员代码面试指南(左程云)读书笔记
第一章
2.编写一个类,用两个栈实现队列,支持队列的基本操作(add 、poll、peek)
import java.util.Stack;
public class MyStack_02_1 {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public MyStack_02_1(){
this.stackPush=new Stack<Integer>();
this.stackPop=new Stack<Integer>();
}
//add
public void add(int pushInt){
stackPush.push(pushInt);
}
//poll
public int poll(){
if(stackPop.empty()&&stackPush.empty()){
throw new RuntimeException("the stack is empty!");
}else if(stackPop.empty()){
while(!stackPush.empty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
//peek
public int peek(){
if(stackPop.empty()&&stackPush.empty()){
throw new RuntimeException("the stack is empty!");
}else if(stackPop.empty()){
while(!stackPop.empty()){
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}