用两个栈实现队列
问题描述:用两个栈实现队列,完成队列的添加(尾部)和删除(头部)操作
本方法思想:本题目主要考察的栈的先入后出的性质,添加的时候用一个栈,弹出的时候用另外一个栈,保证出栈的一定是最先添加的,具体的分析在代码中有注释,直接去看代码吧。
持续更新...
代码附下
Java实现:
package 两个栈构建一个队列;
/**
* 用两个栈构建一个队列
* @author user
*/
import java.util.Stack;
public class Test<T> {
public Stack<T> stack1 = new Stack<T>();
public Stack<T> stack2 = new Stack<T>();
public void addEle(T t) {
System.out.println(t + "已经被压入");
stack1.push(t);
}
public void removeEle() throws Exception {
// 删除的时候 先把stack1的所有元素压入Stack2
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
// 如果stack2为空 说明stack1也为空,无法删除抛出异常
if (stack2.isEmpty()) {
throw new Exception("队列已经为空了,不能删除!");
}
System.out.println(stack2.pop() + "已经被删除");
}
public static void main(String[] args) throws Exception {
Test<Integer> sTest = new Test<Integer>();
sTest.addEle(1);
sTest.addEle(2);
sTest.addEle(3);
sTest.addEle(4);
sTest.removeEle();
sTest.removeEle();
sTest.addEle(5);
sTest.addEle(6);
sTest.removeEle();
sTest.removeEle();
sTest.removeEle();
sTest.removeEle();
}
}
持续更新...欢迎赞赏!![](https://i-blog.csdnimg.cn/blog_migrate/ca0cc5c488ad24501c0bbddad6302b17.png)
https://blog.csdn.net/ustcer_93lk/article/details/80367891
如果有问题,欢迎大家留言,有更好的方法也期待大家告知。