/**
* 编写一个类,要求两个栈实现一个队列,并且重写add、poll、peek
* @author yyq
*
*/
public class StackQueueDemo {
private Stack<Integer> stackPush = new Stack<>();
private Stack<Integer> stackPop = new Stack<>();
public void add(Integer data){
this.stackPush.push(data);
}
public Integer poll(){
if(stackPush.isEmpty()){
throw new RuntimeException("stack is empty");
}
if(stackPush.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
Integer value = stackPop.pop();
while(!stackPop.isEmpty()){
stackPush.push(stackPop.pop());
}
return value;
}
public Integer peek(){
if(stackPush.isEmpty()){
throw new RuntimeException("stack is empty");
}
if(stackPop.isEmpty()){
while(!stackPush.isEmpty()){
stackPop.push(stackPush.pop());
}
}
Integer value = stackPop.peek();
while(!stackPop.isEmpty()){
stackPush.push(stackPop.pop());
}
return value;
}
}