刷
July-06-2019
和133一样
先收集所有的NODE,建立一套新的,此时新的直接没有指针关系。
遍历新的,通过VAL来找到原来的NODE,看看原来NODE指向哪,就把当前指向新的那个位置。
public Node copyRandomList(Node head) {
if (head == null) return null;
Map<Integer, Node> nodes = new HashMap<>();
Node temp = head;
while (temp != null) {
if (!nodes.containsKey(temp.val)) {
nodes.put(temp.val, temp);
}
temp = temp.next;
}
Map<Integer, Node> copies = nodes.entrySet().stream().collect(
Collectors.toMap(
entry -> entry.getKey(),
entry -> new Node(entry.getKey(), null, null)
));
copies.entrySet().stream().forEach(entry -> {
int key = entry.getKey();
Node newNode = entry.getValue();
Node oldNode = nodes.get(key);
if (oldNode.next != null) {
newNode.next = copies.get(oldNode.next.val);
}
if (oldNode.random != null) {
newNode.random = copies.get(oldNode.random.val);
}
});
return copies.get(head.val);
}
Map<String, Long> result2 = list.stream().collect(
Collectors.toMap(Hosting::getName, Hosting::getWebsites));
Map<Integer, String> result3 = list.stream().collect(
Collectors.toMap(x -> x.getId(), x -> x.getName()));