版权声明:be the one ~you will be the one~~ https://blog.csdn.net/Hqxcsdn/article/details/87813985
使用栈实现队列的先进先出功能
栈 stack 是一种 先进后出的数据结构,而队列时先进先出的。所以可以试想使用两个栈。
假设栈 a,栈 b,栈a中依次压入1,2,3,4 现在要将压入的数字按其压入的顺序输出,可以将栈a依次弹出,然后压入 栈b,这样,在b中的顺序就是 4,3,2,1 ,接着 将栈bpush即可,最后输出的顺序就是 1,2,3,4 与队列相同 。若是要往队列中加入元素,即直接向栈a中加入即可。
代码如下
import java.util.Stack;
/**
*
*/
/***
* @author 18071
* @Date 2019年2月20日
* 功能: 使用数据结构栈,实现队列的先进先出功能。
***/
public class test {
public static void main(String args[]) {
quen q=new quen ();
q.add(1);
q.add(2);
q.add(3);
q.add(6);
while(q.st1!=null||q.st2!=null) {
q.putout();
}
}
}
class quen{
Stack st1=new Stack();
Stack st2 =new Stack();
public void add(int x) {
st1.push(x);
}
public void putout() {
if(!st1.isEmpty() ||!st2.isEmpty()) {
if(!st2.isEmpty()) {
int y=(int) st2.pop();//st2出栈即可
System.out.println(y+"出栈");
}
else {
//将st1依次出栈,放入st2中,然后在出栈
while(!st1.isEmpty()) {
int x=(int) st1.pop();
st2.push(x);
}
}
}
}
}
结果截图