在数据结构中,可以使用两个队列实现一个栈,也可以使用两个栈实现一个队列,代码实现如下:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Practice {
//两个队列实现一个栈
private static Queue<Integer> queue1 = new LinkedList<>();
private static Queue<Integer> queue2 = new LinkedList<>();
public static void pushStack(int value){
if(queue1.isEmpty() && queue2.isEmpty()){
queue1.add(value);
}else if(queue1.isEmpty()){
queue2.add(value);
}else if(queue2.isEmpty()){
queue1.add(value);
}
}
public static int popStack(){
Queue<Integer> popQueue = queue1.isEmpty() ? queue2 : queue1;
Queue<Integer> pushQueue = queue1.isEmpty() ? queue1 : queue2;
while(popQueue.size() > 1){
pushQueue.add(popQueue.remove());
}
return popQueue.remove();
}
//两个栈实现一个队列
private static Stack<Integer> stack1 = new Stack<>();
private static Stack<Integer> stack2 = new Stack<>();
public static void pushQueue(int value){
stack1.push(value);
}
public static int popQueue(){
if(stack1.isEmpty() && stack2.isEmpty()){
throw new UnsupportedOperationException("the queue is empty");
}
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public static void main(String[] args) {
pushQueue(10);
pushQueue(20);
pushQueue(30);
pushQueue(40);
System.out.println(popQueue());
System.out.println(popQueue());
System.out.println(popQueue());
pushQueue(50);
pushQueue(60);
System.out.println(popQueue());
System.out.println(popQueue());
System.out.println(popQueue());
System.out.println();
pushStack(10);
pushStack(20);
pushStack(30);
System.out.println(popStack());
pushStack(40);
pushStack(50);
System.out.println(popStack());
System.out.println(popStack());
}
}
运行结果:
10
20
30
40
50
60
30
50
40