/* * 时间: 2021-05-31 23:13 * 分析: 1) 题干中链表的表示方法, 构造单项链表即可 * 思路: */ import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNextInt()) { int cnt = sc.nextInt(); Node head = new Node(sc.nextInt()); // 错写成 i < cnt for (int i = 0; i < cnt - 1; i++) { head.insert(new Node(sc.nextInt()), sc.nextInt()); } head = head.delete(sc.nextInt()); if (head == null) { System.out.println("null"); } Node iter = head; while (iter != null) { System.out.print(iter.val + " "); iter = iter.next; } System.out.println(); } } } class Node { int val; Node next; Node(int val) { this.val = val; this.next = null; } public void insert(Node node, int target) { Node cursor = this; // 错写成 target != node.val while (target != cursor.val) { cursor = cursor.next; } node.next = cursor.next; cursor.next = node; } public Node delete(int val) { Node cursor = this; // 节点头 if (cursor.val == val) { return cursor.next; } while (cursor.next != null) { Node last = cursor; cursor = cursor.next; if (cursor.val == val) { last.next = cursor.next; break; } } return this; } }