138. Copy List With Random Pointer

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.

解法1: HashMap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list with a random pointer.
* class RandomListNode {
* int label;
* RandomListNode next, random;
* RandomListNode(int x) { this.label = x; }
* };
*/
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return head;
}
Map<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode oldHead = head;
while (head != null) {
RandomListNode copy = new RandomListNode(head.label);
map.put(head, copy);
head = head.next;
}
head = oldHead;
while (head != null) {
map.get(head).random = map.get(head.random);
if (head.next != null) {
map.get(head).next = map.get(head.next);
}
head = head.next;
}
return map.get(oldHead);
}
}