用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型
思路:栈先进后出,队列先进先出,通过第二个栈来改变第一个栈的顺序。
实例化时,先new两个栈,进栈统一先进入1栈,出栈时,作一个检测,如果二栈不为空,元素直接出栈,二栈为空,则先将1栈的元素循环出栈,进入2栈。
栈与队列的存取必然要考虑空与满的情况。
/**
* 两个栈实现队列
*/
public class TwoStacksImplQueue {
private Stack<Integer> a;
private Stack<Integer> b;
public TwoStacksImplQueue(){
a = new Stack<Integer>();
b = new Stack<Integer>();
}
public void push(int node){
a.add(node);
}
/**
*出栈,将一个栈用来接元素,然后通过另一个栈来改变顺序
* 如果另一栈存在元素,则直接退出
* 不存在则将第一个栈元素退到第二栈
* @return
*/
public int pop(){
if (a.isEmpty() && b.isEmpty()){
throw new RuntimeException("队列为空");
}
if (b.isEmpty()){
while (!a.isEmpty()){
b.push(a.pop());
}
}
return b.pop();
}
2,用两个队列实现一个栈
队列先进先出,栈先进后出,因此选择通过两个队列交替存储数据,取数据时作一次移动,将有值队列的最后一个数取出,存数据时存入有值队列,都无值则存入任意一个对列;
代码如下:
/**
* 两个队列模拟栈
*/
public class TwoQueueImplStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
public TwoQueueImplStack(){
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
/**
* 插入的时候如果队列都为空,则插入1队列
* 如果其中一个不为空,则插入不为空的队列
*/
public void push(int node){
if (queue1.isEmpty() && queue2.isEmpty()){
queue1.add(node);
}else if (!queue1.isEmpty()){
queue1.add(node);
}else {
queue2.add(node);
}
System.out.println(queue1);
}
/**
* 出栈则判断哪个不为空,将所有其他元素移到另一个队列
* @return
*/
public int pop(){
if (queue1.isEmpty() && queue2.isEmpty()){
throw new RuntimeException("队列为空");
}
if (!queue1.isEmpty()){
while (queue1.size() > 1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}else {
while (queue2.size() > 1){
queue1.add(queue2.poll());
}
return queue2.poll();
}
}