首先我们需要知道栈和队列的特性,即 栈:先进后出;队列:先进先出,通过引入数组中的数据,实现:
1.两个栈实现一个队列
思路: 定义两个栈stack1、stack2,将数组中的数据依次置入stack1中,根据栈先进后出的特性,再将其依次出栈在入栈至stack2中,以实现队列。
- 代码如下:
//两个栈实现一个队列
public static<T> void twoStackToOneQueue(T[] arr){
Stack<T> stack1=new Stack<>();
Stack<T> stack2=new Stack<>();
for(int i=0;i<arr.length;i++) {
stack1.push(arr[i]);
}
while(!stack1.isEmpty()){
stack2.push(stack1.peek());
stack1.pop();
}
while(!stack2.isEmpty()){
System.out.print(stack2.peek()+" ");
stack2.pop();
}
}
public static void main(String[] args) {
Integer[] arr={4,7,5,3,6,8,1};
twoStackToOneQueue(arr);
}
运行结果:
2.两个队列实现一个栈
思路: 定义两个队列queue1、queue2,将数组元素依次入queue1队,再将queue1中元素除最后一个依次入queue2,同样将queue2中元素除最后一个依次入queue1,重复上两步直至队列为空。
- 代码如下:
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]);
}
while(queue1.getSize()!=0) {
while(queue1.getSize() > 1) {
queue2.push(queue1.peek());
queue1.pop();
}
System.out.print(queue1.peek()+" ");
queue1.pop();
if(queue2.getSize()!=0) { //防止queue2空栈异常
while (queue2.getSize() > 1) {
queue1.push(queue2.peek());
queue2.pop();
}
System.out.print(queue2.peek() + " ");
queue2.pop();
}
}
}
public static void main(String[] args) {
Integer[] arr={4,7,5,3,6,8,1};
twoQueueToOneStack(arr);
}
运行结果:
3.判断当前序列是否为arr序列的出栈序列
思路: ①将arr数组中的数据入stack栈
②同时比较其栈顶元素与所谓出栈序列中对应的值,若相同,则出栈
重复上述①②操作,直至栈空。
public static <T>boolean isStackOutOrder(T[] arr,T[] Order){
Stack<T> stack=new Stack<>();
for (int i = 0, j = 0; i < arr.length; i++) {
stack.push(arr[i]);
while(!stack.isEmpty() && stack.peek() == Order[j]) {
stack.pop();
j++;
}
}
if(stack.isEmpty()){
System.out.print("true");
return true;
}else{
System.out.print("false");
return false;
}
}
public static void main(String[] args){
Integer[] arr={1,2,3,4,5};
Integer[] order1={4,5,3,2,1};
Integer[] order2={1,2,3,4,5};
Integer[] order3={1,2,5,3,4};
isStackOutOrder(arr,order1);
System.out.println();
isStackOutOrder(arr,order2);
System.out.println();
isStackOutOrder(arr,order3);
}
该代码以boolean数据类型true / false 返回
运行结果: