-
Notifications
You must be signed in to change notification settings - Fork 118
/
138.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>
struct RandomListNode {
int label;
struct RandomListNode *next;
struct RandomListNode *random;
};
/*
* http://www.geeksforgeeks.org/a-linked-list-with-next-and-arbit-pointer/
*/
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
if (head == NULL) return NULL;
struct RandomListNode *new_node = NULL;
struct RandomListNode *p = head;
/* original next points to new_node, new_node->next points to original next */
while (p) {
new_node = (struct RandomListNode *)malloc(sizeof(struct RandomListNode));
new_node->label = p->label;
new_node->next = p->next;
p->next = new_node;
p = new_node->next;
}
/* link random pointers */
p = head;
struct RandomListNode *new_head = head->next;
struct RandomListNode *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;
}
}
return new_head;
}
int main() {
struct RandomListNode *head
= (struct RandomListNode *)malloc(4 * sizeof(struct RandomListNode));
struct RandomListNode *one = head;
one->label = 1;
struct RandomListNode *two = head + 1;
two->label = 2;
struct RandomListNode *three = head + 2;
three->label = 3;
struct RandomListNode *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;
struct RandomListNode *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;
}
struct RandomListNode *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;
}
return 0;
}