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
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
|
/**
* 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)
return
NULL;
//使用map记录新旧节点映射关系。。。。。。。。。。。。。。。。。。
map<RandomListNode*, RandomListNode*> mp;
RandomListNode* chead =
new
RandomListNode(head->label);
mp.insert(pair<RandomListNode*, RandomListNode*>(head, chead));
RandomListNode* p = head;
RandomListNode* q = chead;
while
(p->next) {
RandomListNode* r =
new
RandomListNode(p->next->label);
q->next = r;
mp.insert(pair<RandomListNode*, RandomListNode*>(p->next, r));
q = q->next;
p = p->next;
}
//接着调整random指针。。。。。。。。。。。。。。。。。。。。。。
p = head;
q = chead;
while
(q){
//map.find(k)如果容器中存在按k索引的元素,则返回指向该元的 迭代器!
//若不存在,返回超出末端 的迭代器
if
(p->random){
q->random = mp.find(p->random)->second;
}
else
q->random = NULL;
p = p->next;
q = q->next;
}
return
chead;
}
};
|