-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCopy List with Random Pointer
More file actions
37 lines (34 loc) · 1.05 KB
/
Copy pathCopy List with Random Pointer
File metadata and controls
37 lines (34 loc) · 1.05 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
/**
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.
**/
class Solution {
public:
RandomListNode *copyRandomList(RandomListNode *head) {
if(head==NULL) return NULL;
RandomListNode *run = head;
while(run!=NULL){
RandomListNode *new_node = new RandomListNode(run->label);
RandomListNode *next = run->next;
run->next = new_node;
new_node->next = next;
run = next;
}
run = head;
RandomListNode *new_head = head->next;
while(run!=NULL){
if(run->random){
run->next->random = run->random->next;
}
run = run->next->next;
}
run = head;
while(run!=NULL){
RandomListNode *next = run->next->next;
run->next->next = next == NULL? NULL : next->next;
run->next = next;
run = next;
}
return new_head;
}
};