Code & Fun

题目是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.

求解思路:

很直观的方法,用来O(n)的空间来保存地址,没想到过了。

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
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head == nullptr) return head;

unordered_map<RandomListNode *, RandomListNode *> m;

RandomListNode *p = head;
RandomListNode copy(0);
RandomListNode *q = &copy;

while(p) {

q->next = new RandomListNode(p->label);

//auto it = m.find(p);
//if (it != m.end()) it->second = q->next;

m[p] = q->next;

p = p->next;
q = q->next;
}

m[nullptr] = nullptr;
p = head;
q = copy.next;

while(p) {

q->random = m[p->random];

p = p->next;
q = q->next;
}

return copy.next;
}
};

share一个dicuss中看到的方法:

图片失效的话,直接去leetcode中看原贴。


本文首发于Code & Fun