- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path138.c
114 lines (98 loc) · 2.48 KB
/
138.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include<stdio.h>
#include<stdlib.h>
structRandomListNode {
intlabel;
structRandomListNode*next;
structRandomListNode*random;
};
/*
* http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/
*/
structRandomListNode*copyRandomList(structRandomListNode*head) {
if (head==NULL) returnNULL;
structRandomListNode*new_node=NULL;
structRandomListNode*p=head;
/* original next points to new_node, new_node->next points to original next */
while (p) {
new_node= (structRandomListNode*)malloc(sizeof(structRandomListNode));
new_node->label=p->label;
new_node->next=p->next;
p->next=new_node;
p=new_node->next;
}
/* link random pointers */
p=head;
structRandomListNode*new_head=head->next;
structRandomListNode*q=NULL;
while (p) {
q=p->next;
if (p->random) {
q->random=p->random->next;
}
else {
q->random=NULL;
}
p=q->next;
}
/* restore original link list */
p=head;
while (p) {
q=p->next;
p->next=q->next;
p=p->next;
if (p) {
q->next=p->next;
}
else {
q->next=NULL;
}
}
returnnew_head;
}
intmain() {
structRandomListNode*head
= (structRandomListNode*)malloc(4*sizeof(structRandomListNode));
structRandomListNode*one=head;
one->label=1;
structRandomListNode*two=head+1;
two->label=2;
structRandomListNode*three=head+2;
three->label=3;
structRandomListNode*four=head+3;
four->label=4;
one->next=two;
two->next=three;
three->next=four;
four->next=NULL;
one->random=three;
two->random=one;
three->random=NULL;
four->random=four;
structRandomListNode*p=head;
printf("N R\n");
while (p) {
printf("%d ", p->label);
if (p->random) {
printf("%d\n", p->random->label);
}
else {
printf("NIL\n");
}
p=p->next;
}
structRandomListNode*new_head=copyRandomList(head);
p=new_head;
printf("Copied:\n");
printf("N R\n");
while (p) {
printf("%d ", p->label);
if (p->random) {
printf("%d\n", p->random->label);
}
else {
printf("NIL\n");
}
p=p->next;
}
return0;
}