package com.my.suanfa;
import java.util.Stack;
/*
* 由两个栈组成的队列
* 向stackPop中压入数据的时机有很多。在这里选择出队和查看队头元素时压入
* 但是压入数据要满足两条:
* 1.只能在stackPop为空时才能压入数据
* 2.如果需要压入数据,则必须将stackPush中的数据全部压入
* */
public class TwoStacksQueue {
//声明变量
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
//初始化变量
public TwoStacksQueue() {
this.stackPush = new Stack<Integer>();
this.stackPop = new Stack<Integer>();
}
//入队操作
public void add(int pushInt) {
this.stackPush.push(pushInt);
}
//出队操作
public int poll() {
//判断队列是否为空
if(this.stackPush.isEmpty() && this.stackPop.isEmpty()) {
throw new RuntimeException("your queue is empty!");
} else if(this.stackPop.isEmpty()) {
while(!this.stackPush.isEmpty()) {
this.stackPop.push(this.stackPush.pop());
}
}
return this.stackPop.pop();
}
//查看队列头的元素
public int peek() {
if(this.stackPop.isEmpty() && this.stackPush.isEmpty()) {
throw new RuntimeException("your queue is empty!");
} else if(this.stackPop.isEmpty()) {
while(!this.stackPush.isEmpty()) {
this.stackPop.push(this.stackPush.pop());
}
}
return this.stackPop.peek();
}
}
002-由两个栈组成的队列
最新推荐文章于 2021-08-30 20:12:31 发布