题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
import java.util.*;
public class Main {
static HashMap<Integer, Integer> map;
static Integer key;
public static void main(String[] args) {
map = new HashMap<>();
Scanner in = new Scanner(System.in);
int n = in.nextInt();//节点数量
int first = in.nextInt();//头结点
map.put(null, first);
for (int i = 0; i < n - 1; i++) {
//读取余下节点
int value = in.nextInt();//新结点的值
int index = in.nextInt();//新结点的位置
if (null == map.get(index)) {//
map.put(index, value);
} else {
map.put(value, map.get(index));
map.put(index, value);
}
}
//删除节点
int remove = in.nextInt();
Integer k = getKey(remove);
Integer value = map.get(remove);
map.remove(remove);
map.put(k, value);
//遍历输出
sout(null);
}
private static Integer getKey(int remove) {
map.forEach((k, v) -> {
if (v.equals(remove)) {
key = k;
}
});
return key;
}
private static void sout(Object o) {
if (null != map.get(o)) {
System.out.print(map.get(o) + " ");
sout(map.get(o));
}
}
}
解题思路:
1, 链表中的数据应是键值对的形式, 所以使用哈希Map来存放数据;
2, 注意插入和删除数据时候的处理