-
Notifications
You must be signed in to change notification settings - Fork 0
/
138.CopyListwithRandomPointer.cpp
64 lines (54 loc) · 1.16 KB
/
138.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
61
62
63
64
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution
{
public:
Node *copyRandomList(Node *head)
{
if (!head)
return nullptr;
Node *temp = head;
// Creating a new list in between
while (temp)
{
Node *copyNode = new Node(temp->val);
copyNode->next = temp->next;
temp->next = copyNode;
temp = copyNode->next;
}
temp = head;
// Placing random pointers
while (temp)
{
if (temp->random)
{
temp->next->random = temp->random->next;
}
temp = temp->next->next;
}
temp = head;
// Removing connections
Node *dummyNode = new Node(-1);
Node *res = dummyNode;
while (temp)
{
res->next = temp->next;
res = res->next;
temp->next = temp->next->next;
temp = temp->next;
}
return dummyNode->next;
}
};