题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int n = in.nextInt(); int headVal = in.nextInt(); // 创建带虚头节点的链表 Node head = new Node(0); Node firstNode = new Node(headVal); head.next = firstNode; for (int i = 0; i < n - 1; i++) { // 当前节点值 int curVal = in.nextInt(); Node curNode = new Node(curVal); // 前一个节点值 int preVal = in.nextInt(); // 查找前一个节点值的父节点,插入需要找到待插入节点的父节点 Node preNode = findPreNodeByVal(head, preVal).next; // 将当前节点值插入到其之后 Node temp = preNode.next; curNode.next = temp; preNode.next = curNode; } // 删除的结点的值 // 删除需要找到待删除节点的父节点 int toDeleteNodeVal = in.nextInt(); Node preNode = findPreNodeByVal(head, toDeleteNodeVal); preNode.next = preNode.next.next; while (head.next != null) { System.out.print(head.next.val + " "); head = head.next; } } } // 根据值查找其前一个节点 private static Node findPreNodeByVal(Node head, int val) { if (head.next == null) { return head; } Node curNode = head; while (curNode.next != null) { if (curNode.next.val == val) { return curNode; } curNode = curNode.next; } return head; } } class Node { int val; Node next; public Node(int val) { this.val = val; } }