-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCopy List.cpp
More file actions
51 lines (45 loc) · 1.24 KB
/
Copy pathCopy List.cpp
File metadata and controls
51 lines (45 loc) · 1.24 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
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for singly-linked list.
* struct RandomListNode {
* int label;
* RandomListNode *next, *random;
* RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
* };
*/
RandomListNode* Solution::copyRandomList(RandomListNode* head) {
if(!head)
return NULL;
RandomListNode* temp=head;
RandomListNode* pt;
// First pass creates a deep copy
while(temp!=NULL){
RandomListNode* p=new RandomListNode(temp->label);
p->next=temp->next;
temp->next=p;
temp=p->next;
}
// connecting the pointers now...
// random ones
RandomListNode* p;
temp=head;
while(temp!=NULL){
p=temp->next;
if(!temp->random)
p->random=NULL;
else
p->random=temp->random->next;
temp=p->next;
}
// next pointers now
p=head->next;
temp=head;
pt=p;
while(temp!=NULL){
temp->next=pt->next;
temp=temp->next;
if(pt->next)
pt->next=temp->next;
pt=pt->next;
}
return p;
}