题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static class Node { private final int val; private Node next; public Node(int val) { this.val = val; //JVM在进行类加载是next会自动初始化为null // this.next=null; } } static class MyList { private final Node dummyHead; public MyList() { dummyHead = new Node(-1); } public void insert(int x, int y) { Node cur = dummyHead; while (true) { if (cur.next == null || cur.next.val == x) { Node newNode = new Node(y); newNode.next = cur.next; cur.next = newNode; break; } cur = cur.next; } } public void delete (int x) { Node cur = dummyHead; while (cur != null) { if (cur.next != null && cur.next.val == x) { Node GCnode = cur.next; cur.next = cur.next.next; /* * 虽然我们逻辑上删除了链表中的结点,但是对象之间的强引用会阻止垃圾收集器回收它们, * 在删除节点后,我们手动设置被删除节点的 next 引用为 null,以便Java的垃圾收集器可以回收该节点。 */ GCnode = null; break; } cur = cur.next; } } public Node getHead() { return dummyHead.next; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in) ); StringBuilder sb = new StringBuilder(); int commandsCount = Integer.parseInt(br.readLine()); MyList list = new MyList(); while (commandsCount > 0) { String[] command = br.readLine().split(" "); if (command[0].equals("insert")) { int x = Integer.parseInt(command[1]); int y = Integer.parseInt(command[2]); list.insert(x, y); } else if (command[0].equals("delete")) { int x = Integer.parseInt(command[1]); list.delete(x); } commandsCount--; } Node cur = list.getHead(); if (cur == null) { sb.append("NULL"); } else { while (cur != null) { sb.append(cur.val).append(" "); cur = cur.next; } } System.out.println(sb); } }