比如我要去实现一个1 2 3 4 5 6 通过两个队列去输出6 5 4 3 2 1.
思想:
一.数组翻转的思想。
二.每次都在空的一端插入,插入完把旧队列反转过来,以此循环
三.使用链表数组来表示队列,可以不用考虑初始化长度。
刚开始插入1.
1 |
---|
插入2
1 | 2 |
---|
插入3
3 | 2 | 1 |
---|
插入4
1 | 2 | 3 | 4 |
---|
插入5
5 | 4 | 3 | 2 | 1 |
---|
插入6
1 | 2 | 3 | 4 | 5 | 6 |
---|
import java.util.LinkedList;
/**
* @author zhangrichao
* @version 创建时间:2019年1月23日 下午4:01:49
* 用两个队列实现一个栈
*/
public class QueueToStack {
LinkedList<Integer> queueA=new LinkedList<Integer>();
LinkedList<Integer> queueB=new LinkedList<Integer>();
//模仿栈的入栈操作
public void push(int value)
{
if(queueA.isEmpty()&&queueB.isEmpty()){
queueA.addLast(value);
}else if(queueA.isEmpty()&&!queueB.isEmpty()){
queueA.addLast(value);
transfer();
}else if(queueB.isEmpty()&&!queueA.isEmpty()){
queueB.addLast(value);
transfer();
}
}
//模仿栈的出栈操作 必须是非空的栈才能出栈啊
public int pop()
{
if(queueA.isEmpty()&&!queueB.isEmpty()){
return queueB.removeFirst();
}
else if(queueB.isEmpty()&&!queueA.isEmpty()){
return queueA.removeFirst();
}
else{
return 0;
}
}
//将旧队列反转放在插入头元素的位置上
public void transfer()
{
//因为默认从队列A插入。所以后面第二个数插入队列B时。要默认B为优先条件,毕竟两个队列的尺寸都为1
if(queueB.size()==1&&!queueA.isEmpty()){
while(!queueA.isEmpty()){
int element=queueA.removeFirst();
queueB.addLast(element);
}
}
if(queueA.size()==1&&!queueB.isEmpty()){
while(!queueB.isEmpty()){
int element=queueB.removeFirst();
queueA.addLast(element);
}
}
}
public static void main(String[] args)
{
QueueToStack stack=new QueueToStack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(5);
stack.push(6);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}