-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcopy-list-with-random-pointer.cpp
More file actions
39 lines (37 loc) · 1 KB
/
copy-list-with-random-pointer.cpp
File metadata and controls
39 lines (37 loc) · 1 KB
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
/**
* 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:
map<RandomListNode *, RandomListNode *> oldToNew;
RandomListNode *copyRandomList(RandomListNode *head) {
if(head == NULL)
return NULL;
RandomListNode *newHead = new RandomListNode(head -> label);
oldToNew[head] = newHead;
RandomListNode *p = head;
RandomListNode *q = newHead;
oldToNew[NULL] = NULL;
while(p -> next)
{
p = p -> next;
q -> next = new RandomListNode(p -> label);
oldToNew[p] = q -> next;
q = q -> next;
}
p = head;
q = newHead;
while(p)
{
q -> random = oldToNew[p -> random];
p = p -> next;
q = q -> next;
}
return newHead;
}
};