题解 | #由两个栈组成的队列#
由两个栈组成的队列
https://www.nowcoder.com/practice/6bc058b32ee54a5fa18c62f29bae9863
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { //第一个栈正常add数据 static Stack<Integer> stack1 = new Stack<>(); //需要peek()或pop()时,把栈1 倒入 栈2 static Stack<Integer> stack2 = new Stack<>(); static Scanner in = new Scanner(System.in); public static void main(String[] args) { int N = in.nextInt(); for (int i = 0; i < N; i++) { String str = in.next(); switch (str) { case "add": add(); break; case "peek": peek(); break; case "poll": poll(); break; default: break; } } } private static void add() { stack1.add(in.nextInt()); } private static void peek() { while (!stack1.isEmpty()) { stack2.add(stack1.pop()); } System.out.println(stack2.peek()); while (!stack2.isEmpty()) { stack1.add(stack2.pop()); } } private static void poll() { while (!stack1.isEmpty()) { stack2.add(stack1.pop()); } stack2.pop(); while (!stack2.isEmpty()) { stack1.add(stack2.pop()); } } }
栈和队列,记录栈和队列的一些题 文章被收录于专栏
栈和队列,记录栈和队列的一些题