/
copy_list_with_random.c
55 lines (51 loc) · 1.21 KB
/
copy_list_with_random.c
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
52
53
54
55
#include<stdlib.h>
struct RandomListNode {
int label;
struct RandomListNode *next;
struct RandomListNode *random;
};
void appendNew(struct RandomListNode* head){
if(!head){
return;
}
struct RandomListNode* current = (struct RandomListNode*)malloc(sizeof(struct RandomListNode));
struct RandomListNode* head_nxt = head->next;
current->label = head->label;
current->next = head_nxt;
current->random = NULL;
head->next = current;
appendNew(head_nxt);
}
void setRandom(struct RandomListNode* head){
if(!head){
return;
}
if(head->random){
head->next->random = head->random->next;
}
setRandom(head->next->next);
}
void restore(struct RandomListNode* head){
if(!head){
return;
}
struct RandomListNode* head_nxt = head->next->next, *copy = head->next;
head->next = head_nxt;
if(head_nxt){
copy->next = head_nxt->next;
}
else{
copy->next = NULL;
}
restore(head_nxt);
}
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
if(!head){
return head;
}
appendNew(head);
setRandom(head);
struct RandomListNode* ans = head->next;
restore(head);
return ans;
}