您的位置:首页 > 其它

两个栈实现一个队列

2017-11-02 17:04 176 查看
/**
* 编写一个类,要求两个栈实现一个队列,并且重写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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: