-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path38. CopyListWithRandomPointer.cpp
60 lines (54 loc) · 1.22 KB
/
38. CopyListWithRandomPointer.cpp
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
LinkedListNode<int> *cloneRandomList(LinkedListNode<int> *head)
{
LinkedListNode<int> *curr = head, *temp = NULL;
while (curr != NULL)
{
temp = curr->next;
curr->next = new LinkedListNode<int>(curr->data);
curr->next->next = temp;
curr = temp;
}
curr = head;
while (curr != NULL)
{
if (curr->next != NULL)
{
if (curr->random != NULL)
{
curr->next->random = curr->random->next;
}
else
{
curr->next->random = curr->random;
}
}
if (curr->next != NULL)
{
curr = curr->next->next;
}
else
{
curr = curr->next;
}
}
LinkedListNode<int> *original = head, *copy = NULL;
if (head != NULL)
{
copy = head->next;
}
temp = copy;
while (original != NULL && copy != NULL)
{
if (original->next != NULL)
{
original->next = original->next->next;
}
if (copy->next != NULL)
{
copy->next = copy->next->next;
}
original = original->next;
copy = copy->next;
}
return temp;
}