首先,要实现这种结构,需要了解这两种数据结构的特性:
栈:是一种 先进后出 的数据结构;
队列:是一种 先进先出 的数据结构;
要仅用其中一种 实现另外一种的特性,那么无论如何都需要用到两个相同的结构来实现;
一.用队列实现栈结构:
用队列实现栈结构,那么就需要创建 两个 队列,一个用来存放数据(push)的队列 取名为dataQueue,另外一个用来实现pop和peek 取名为helpQueue;
每次在需要pop或者peek出栈顶元素时,就将dataQueue中的元素依次放进helpQueue中,此时仅在dataQueue中留下需要pop或者peek的元素,也就是仅留下队尾的元素。
1.如果这个元素是被pop的,那么就调用队列的poll()方法,将该元素弹出,并从队列中删除;
2.如果这个元素是被peek的,那么peek后,就需要将这个元素加入到helpQueue当中;
完成这一系列操作后,在下一次操作前,需要将dataQueue的引用于helpQueue的引用交换位置;
二.用栈实现队列结构:
用栈实现队列也是需要创建两个栈,一个栈用来push 取名为pushStack,一个栈用来pop 取名为popStack,当需要pop时,就把pushStack栈中的所有元素全部移到pop栈中,然后在弹出popStack栈 栈顶的元素(peek也如此,只不过不弹出,只展示而已),这样就得到了队首的元素。
如果此时pushStack中又新填了元素需要移到popStack栈中,那么需要判断popStack栈是否为空,如果不为空,就不能移入(因为如果移入进去,队首的元素就会发生改变),如果为空,方可移入。
下面上代码:(觉得还可以的老铁们,点个赞在走噢)
public class Queue_Stack_Convert
{
//两个队列实现一个栈结构
public static class TwoQueueConvertStack
{
private static Queue<Integer> dataQueue;
private static Queue<Integer> helpQueue;
public TwoQueueConvertStack()
{
dataQueue = new LinkedList<>();
helpQueue = new LinkedList<>();
}
public static void push(Integer obj)
{
dataQueue.add(obj);
}
public static Integer pop()
{
if (dataQueue.isEmpty()) throw new ArrayIndexOutOfBoundsException("The Stack's length less 0 ");
while (dataQueue.size()>1)
{
helpQueue.add(dataQueue.poll());
}
int ele = dataQueue.poll();
swap();
return ele;
}
public static Integer peek()
{
if (dataQueue.isEmpty()) throw new ArrayIndexOutOfBoundsException("The Stack's length less 0 ");
while (dataQueue.size()>1)
{
helpQueue.add(dataQueue.poll());
}
int ele = dataQueue.poll();
helpQueue.add(ele);
swap();
return ele;
}
//交换两个队列
public static void swap()
{
Queue<Integer> temp = helpQueue;
helpQueue = dataQueue;
dataQueue = temp;
}
public static void main(String[] args) {
TwoQueueConvertStack T = new TwoQueueConvertStack();
push(1);
push(2);
push(3);
push(4);
push(5);
push(6);
System.out.println(peek());
System.out.println(pop());
System.out.println(pop());
}
}
//两个栈实现一个队列结构
public static class TwoStackConvertQueue{
private static Stack<Integer> popStack;
private static Stack<Integer> pushStack;
public TwoStackConvertQueue()
{
popStack = new Stack<>();
pushStack = new Stack<>();
}
public static void push(Integer obj)
{
pushStack.push(obj);
}
public static Integer pop()
{
if (popStack.isEmpty()&&pushStack.isEmpty()) throw new IllegalArgumentException("The Queue is not empty");
if (popStack.isEmpty())
{
while (!pushStack.isEmpty())
{
popStack.push(pushStack.pop());
}
}
return popStack.pop();
}
public static Integer peek()
{
if (popStack.isEmpty()&&pushStack.isEmpty()) throw new IllegalArgumentException("The Queue is not empty");
if (popStack.isEmpty())
{
while (!pushStack.isEmpty())
{
popStack.push(pushStack.pop());
}
}
return popStack.peek();
}
public static void main(String[] args) {
TwoStackConvertQueue T = new TwoStackConvertQueue();
push(1);
push(2);
push(3);
push(4);
push(5);
System.out.println(peek());
System.out.println(peek());
System.out.println("pop:====");
System.out.println(pop());
System.out.println(pop());
}
}