-
Notifications
You must be signed in to change notification settings - Fork 0
/
copy_list_with_random_pointer.cpp
118 lines (104 loc) · 2.44 KB
/
copy_list_with_random_pointer.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
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
115
116
117
118
// =====================================================================================
//
// Filename: copy_list_with_random_pointer.cpp
//
// Description: 138. Copy List with Random Pointer.
//
// Version: 1.0
// Created: 09/10/2019 08:34:53 PM
// Revision: none
// Compiler: g++
//
// Author: Zhu Xianfeng (), [email protected]
// Organization:
//
// =====================================================================================
#include <stdio.h>
class Node
{
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random)
{
val = _val;
next = _next;
random = _random;
}
};
class Solution
{
public:
Node* copyRandomList(Node* head)
{
if (head == nullptr)
{
return nullptr;
}
int num = 0;
Node* copy = nullptr;
Node* ptr1 = head;
Node* ptr2 = nullptr;
Node* tail1 = nullptr;
Node* tail2 = nullptr;
// Copy linked list
while (ptr1 != nullptr)
{
auto* node = new Node(ptr1->val, nullptr, nullptr);
if (ptr2 == nullptr)
{
copy = node;
}
else
{
ptr2->next = node;
}
num++;
ptr2 = node;
tail1 = ptr1;
tail2 = ptr2;
ptr1 = ptr1->next;
}
// Link tail and head
tail1->next = head;
tail2->next = copy;
// Copy random pointer
ptr1 = head;
ptr2 = copy;
while (num > 0)
{
if (ptr1->random == nullptr)
{
ptr2->random = nullptr;
}
else
{
auto* p = ptr1;
auto* q = ptr2;
while (p != ptr1->random)
{
p = p->next;
q = q->next;
}
// Found random
ptr2->random = q;
}
ptr1 = ptr1->next;
ptr2 = ptr2->next;
num--;
}
// Unlink tail and head
tail1->next = nullptr;
tail2->next = nullptr;
return copy;
}
};
int main(int argc, char* argv[])
{
Node* head = nullptr;
Node* copy = Solution().copyRandomList(head);
printf("Finish copy: %p\n", copy);
return 0;
}