Star

LeetCode 138. Copy List with Random Pointer

Question

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.

Explanation

这道题有两种解法。一种用Hashmap存每个节点,然后复制。这种需要占用Extra space。另外一种就是把每个新的节点存到原来的节点的下一个,不用额外空间。

Code

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class Solution {
// Solution 1: using hashmap and iterate twice. one for nodes, the other for next and random.
public RandomListNode copyRandomList(RandomListNode head) {
HashMap<RandomListNode, RandomListNode> map = new HashMap<>();
RandomListNode curr = head;
// copy the all the nodes and their labels first
while (curr != null) {
map.put(curr, new RandomListNode(curr.label));
curr = curr.next;
}
RandomListNode node = head;
// copy all the next and randoms
while (node != null) {
map.get(node).next = map.get(node.next);
map.get(node).random = map.get(node.random);
node = node.next;
}
return map.get(head);
}
// Solution 2: no hashmap, only linked list
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) return null;
RandomListNode curr = head;
// copy next
while (curr != null) {
RandomListNode newNode = new RandomListNode(curr.label);
newNode.random = curr.random;
newNode.next = curr.next;
curr.next = newNode;
curr = curr.next.next;
}
// copy random
RandomListNode cur = head;
while (cur != null) {
if (cur.next.random != null) {
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
// split list
RandomListNode newHead = head.next;
RandomListNode curt = head;
while (curt != null) {
RandomListNode tmp= curt.next;
curt.next = tmp.next;
curt = curt.next;
if (tmp.next != null) {
tmp.next = tmp.next.next;
}
}
return newHead;
}
}