题解 | #从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
java hashMap
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while (sc.hasNextInt()) {
int n = sc.nextInt();
if (n == 1) {
continue;
}
Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
int start = sc.nextInt();
map.put(start, null);
for (int i = 0; i < n-1; i++) {
int next = sc.nextInt();
int cur = sc.nextInt();
if (map.containsKey(cur)) {
map.put(next, map.get(cur));
}
map.put(cur, next);
}
int delete = sc.nextInt();
if (delete == start) {
start = map.get(start);
map.remove(delete);
} else {
int b = start;
int a = map.get(start);
for (int i = 0; i < map.size() - 1; i++) {
if (a == delete) {
map.put(b, map.get(a));
map.remove(a);
break;
} else {
b = a;
a = map.get(a);
}
}
}
System.out.print(start);
int c = start;
while (map.get(c) != null) {
System.out.print(" " + map.get(c));
c = map.get(c);
}
}
}
}