题解 | 从单向链表中删除指定值的节点
核心思路:
- 主要考察链表的插入和删除
- 链表插入比较好搞,直接变更引用的执行即可
- 链表的插入需要注意删除头节点的时候,由于Java的传参也是传递的引用的副本,变更头节点引用时,需要重新赋值后的头节点返回
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Node head = new Node(in.nextInt()); while (in.hasNextInt() && n > 1) { int a = in.nextInt(); int b = in.nextInt(); insert(head, b, a); n--; } int delVal = in.nextInt(); head = del(head, delVal); while (head != null) { System.out.print(head.val + " "); head = head.next; } } public static void insert(Node head, int i, int target) { Node tmp = head; while (tmp.val != i) { tmp = tmp.next; } Node newNode = new Node(target); newNode.next = tmp.next; tmp.next = newNode; } public static Node del(Node head, int target) { // 如果要删除的是头节点 if (head.val == target) { head = head.next; return head; } Node tmp = head; Node pre = new Node(0); while (tmp.val != target) { pre = tmp; tmp = tmp.next; } pre.next = tmp.next; tmp.next = null; return head; } } class Node { int val; Node next; public Node(int val) { this.val = val; } }