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

程序员代码面试指南(左程云)读书笔记

第一章

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

import java.util.Stack;


public class MyStack_02_1 {
public Stack stackPush;
public Stack stackPop;
public MyStack_02_1(){
this.stackPush=new Stack();
this.stackPop=new Stack();
}
//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();
}
}

你可能感兴趣的:(数据结构)