8000 Refine · hiteshmewada/leetcode@8354b9a · GitHub
[go: up one dir, main page]

Skip to content

Commit 8354b9a

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent c4372d3 commit 8354b9a

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

138_copy_list_with_random_pointer/copy_list.c

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -9,35 +9,31 @@ struct Node {
99

1010
static struct Node *copyRandomList(struct Node *head)
1111
{
12-
if (head == NULL) {
13-
return NULL;
14-
}
15-
16-
/* copy and redirect next pointer */
17-
struct Node *p, *new;
18-
for (p = head; p != NULL; p = p->next->next) {
19-
new = malloc(sizeof(*new));
20-
new->val = p->val;
21-
new->next = p->next;
22-
p->next = new;
12+
struct Node *p, *q;
13+
/* insert interleavingly */
14+
for (p = head; p != NULL; p = q->next) {
15+
q = malloc(sizeof(*q));
16+
q->val = p->val;
17+
q->next = p->next;
18+
p->next = q;
2319
}
2420

2521
/* clone random pointer */
26-
for (p = head; p != NULL; p = p->next->next) {
27-
new = p->next;
28-
new->random = p->random != NULL ? p->random->next : NULL;
22+
for (p = head; p != NULL; p = q->next) {
23+
q = p->next;
24+
q->random = p->random != NULL ? p->random->next : NULL;
2925
}
3026

3127
struct Node dummy;
3228
struct Node *prev = &dummy;
33-
for (p = head; p != NULL; p = p->next) {
34-
new = p->next;
35-
p->next = new->next;
36-
/* correct the actual next pointer of the new list */
37-
prev->next = new;
38-
prev = new;
39-
new->next = NULL;
29+
prev->next = head;
30+
for (p = head; p != NULL; p = q->next) {
31+
q = p->next;
32+
/* separate q list */
33+
prev->next = q;
34+
prev = q;
4035
}
36+
/* q->next = NULL */
4137

4238
return dummy.next;
4339
}

0 commit comments

Comments
 (0)
0