题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
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); int n = in.nextInt(); Node head = new Node(in.nextInt()); Node dummy = new Node(-1, head); while (in.hasNextInt()) { Node target = new Node(in.nextInt()); // 插入/删除的结点 if (in.hasNextInt()) { // 插入 int insert = in.nextInt(); Node node = dummy; while (node != null) { if (node.val == insert) { target.next = node.next; node.next = target; break; } node = node.next; } } else { // 删除 Node node = dummy; while (node.next != null) { if (node.next.val == target.val) { node.next = node.next.next; break; } node = node.next; } } } System.out.println(head.toString()); } } class Node { public Node() { } public Node(int val, Node next) { this.val = val; this.next = next; } public Node(int val) { this.val = val; } int val; Node next; @Override public String toString() { StringBuilder sb = new StringBuilder(); Node node = this; while (node != null) { sb.append(node.val).append(" "); node = node.next; } return String.valueOf(sb); } }