我们都知道一维数组可以在栈和队列中进行存入和取出操作,并且由于各自的特殊性,同样的数列(1,2,3,4,5)进入栈或进入队列后,他们的输出序列是不一样的。栈的规则是先进后出(输出5,4,3,2,1,),而队列的规则是先进先出(输出还是1,2,3,4,5)。
那么我们如何实现栈和队列的相互转化呢?
1.两个栈表示一个队列
两个栈想要表示一个队列对于一维数组的操作方式,只需要进行两次压入栈和弹出栈的操作即可。即((1,2,3,4,5)入栈1,出栈1为(5,4,3,2,1,),在入栈2,出栈2为(1,2,3,4,5))
图解如下:
具体的代码实现为:
public static <T> void twoStackToOneQueue(T[] arr){
Stack<T> str1=new Stack<>();
Stack<T> str2=new Stack<>();
for(int i=0;i<arr.length;i++){
str1.push(arr[i]);
}
while(!str1.isEmpty()){
str2.push(str1.peek());
str1.pop();
}
while(!str2.isEmpty()){
System.out.println(str2.peek()+"");
str2.pop();
}
}
public static void main(String args[]) {
twoStackToOneQueue(new Integer[]{1, 2, 3, 4, 5, 6});
}
}
2.两个队列表示一个栈
两个队列想要表示一个栈,这里需要用到在两个队列间循环入队出队的操作,由于队列先入先出的性质,每次只需要将队列的最后一个元素弹出,就可以反向实现输出序列的效果,即(1,2,3,4,5)——>(5,4,3,2,1,)
图解如下:
具体的代码实现为:
public static<T> void twoQueueToOneStack(T[] arr) {
MyQueue<T> queue1 = new MyQueue<>();
MyQueue<T> queue2 = new MyQueue<>();
for (int i = 0; i < arr.length; i++) {
queue1.push(arr[i]);
}
int scrLength = arr.length;
while (scrLength > 0) {
while (queue1.size() > 1) {
queue2.push(queue1.peek());
queue1.pop();
}
System.out.println(queue1.peek() + " ");
queue1.pop();
scrLength--;
if (scrLength != 0) {
while (queue2.size() > 1) {
queue1.push(queue2.peek());
queue2.pop();
}
System.out.println(queue2.peek() + " ");
queue2.pop();
scrLength--;
}
}
}
public static void main(String[]args){
twoQueueToOneStack(new Integer []{1,2,3,4,5,6});
}
}
如有错误的地方,请您不吝赐教!