题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.util.*;
// 注意类名必须为 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 num = in.nextInt();
int headVal = in.nextInt();
Node head = new Node(headVal);
HashMap<Integer, Node> map = new HashMap<>();
map.put(headVal, head);
// 创建链表,并用hashmap来记录当前节点数量和快速寻找对应节点,以便添加新节点
while (map.size() < num) {
int val = in.nextInt();
int prev = in.nextInt();
Node newNode = new Node(val);
if (map.get(prev).next != null) {
Node temp = map.get(prev).next;
map.get(prev).next = newNode;
newNode.next = temp;
} else {
map.get(prev).next = newNode;
}
map.put(val, newNode);
}
// 遍历链表,如果遇到需要移除的节点则不print
int removeVal = in.nextInt();
while (head != null) {
if (head.val != removeVal)
System.out.print(head.val + " ");
head = head.next;
}
}
}
}
class Node {
int val;
Node next;
public Node(int val) {
this.val = val;
this.next = null;
}
}


