-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105.h
35 lines (34 loc) · 1007 Bytes
/
105.h
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
/**
* 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:
/**
* @param head: The head of linked list with a random pointer.
* @return: A new head of a deep copy of the list.
*/
RandomListNode *copyRandomList(RandomListNode *head) {
// write your code here
map<RandomListNode*,RandomListNode*> m;
RandomListNode dummyhead(0);
RandomListNode *cur = &dummyhead;
RandomListNode *tmp = head;
while(tmp != nullptr){
cur->next = new RandomListNode(tmp->label);
cur = cur->next;
m[tmp] = cur;
tmp = tmp->next;
}
tmp = head;
while(tmp != nullptr){
m[tmp]->random = m[tmp->random];
tmp = tmp->next;
}
return dummyhead.next;
}
};