1.用两个栈实现队列

java
import java.util.*;
public class Solution {
// 入队栈:负责接收新元素
private Stack<Integer> stackIn = new Stack<>();
// 出队栈:负责弹出元素
private Stack<Integer> stackOut = new Stack<>();
// 入队操作:直接压入入队栈
public void push(int node) {
stackIn.push(node);
}
// 出队操作:保证先进先出
public int pop() {
// 出队栈为空时,将入队栈所有元素转移到出队栈
if (stackOut.isEmpty()) {
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());
}
}
// 弹出出队栈栈顶(队列队头)
return stackOut.pop();
}
public static void main(String[] args) {
Solution queue = new Solution();
Scanner sc = new Scanner(System.in);
// 读取操作序列
String[] ops = sc.nextLine().split(",");
List<Integer> res = new ArrayList<>();
for (String op : ops) {
if (op.startsWith("PSH")) {
// 入队操作:提取数字
int num = Integer.parseInt(op.substring(3));
queue.push(num);
} else if (op.equals("POP")) {
// 出队操作:记录结果
res.add(queue.pop());
}
}
// 输出结果,用逗号分隔
for (int i = 0; i < res.size(); i++) {
if (i > 0) System.out.print(",");
System.out.print(res.get(i));
}
}
}