题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
import java.util.LinkedList; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { private static LinkedList<Integer> list = new LinkedList<>(); public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 final int NUM = in.nextInt(); for (int i = 0; i != NUM; ++i) { String op = in.next(); if (op.equals("insert")) { int x = in.nextInt(); int y = in.nextInt(); int indexOfX = list.indexOf(x); if (indexOfX == -1) { list.addLast(y); } else if (indexOfX == 0) { list.addFirst(y); } else { list.add(indexOfX, y); } } if (op.equals("delete")) { int x = in.nextInt(); list.removeFirstOccurrence(x); } } if (list.isEmpty()) { System.out.println("NULL"); } else { for (int x : list) { System.out.print(x + " "); } } } }