A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
題意給定一個鍊表,每個節點包含一個額外增加的隨機指針,該指針可以指向鍊表中的任何節點或空節點。我們用一個由 n 個節點組成的鍊表來表示輸入/輸出中的鍊表。每個節點用一個 [val, random_index] 表示:random_index:隨機指針指向的節點索引(範圍從 0 到 n-1);如果不指向任何節點,則為 null 。
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
HashMap<Node, Node> map = new HashMap<>();
Node h = head;
while (h != null) {
Node t = new Node(h.val);
map.put(h, t);
h = h.next;
}
h = head;
while (h != null) {
if (h.next != null) {
map.get(h).next = map.get(h.next);
}
if (h.random != null) {
map.get(h).random = map.get(h.random);
}
h = h.next;
}
return map.get(head);
}