-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0138-copy-list-with-random-pointer.c
89 lines (75 loc) · 2.06 KB
/
0138-copy-list-with-random-pointer.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
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
/*
Time: O(n)
Space: O(1)
*/
typedef struct Node Node;
struct Node* copyRandomList(struct Node* head) {
if(head == NULL)
{
return NULL;
}
/**
* Insert each new node after each original node
*/
Node* curr = head;
while(curr)
{
// Create the new node
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->val = curr->val;
// Insert new node after the original node
newNode->next = curr->next;
curr->next = newNode;
// Move curr to the next original node
curr = curr->next->next;
}
/**
* Add the random node for each new node
*/
curr = head;
Node* newNode = NULL;
while(curr)
{
// The new node is the next node to the original node
newNode = curr->next;
if(curr->random)
{
newNode->random = curr->random->next;
}
else
{
newNode->random = NULL;
}
// Move curr to the next original node
curr = curr->next->next;
}
/**
* Separate the original nodes list from the new nodes list
*/
Node* originalList = head;
Node* copiedList = head->next;
Node* copiedListHead = head->next;
while(originalList)
{
originalList->next = originalList->next->next;
if(copiedList->next)
{
copiedList->next = copiedList->next->next;
}
else
{
copiedList->next = NULL;
}
originalList = originalList->next;
copiedList = copiedList->next;
}
return copiedListHead;
}