-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.copy-list-with-random-pointer.cpp
More file actions
67 lines (59 loc) · 1.33 KB
/
138.copy-list-with-random-pointer.cpp
File metadata and controls
67 lines (59 loc) · 1.33 KB
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
/*
* @lc app=leetcode id=138 lang=cpp
*
* [138] Copy List with Random Pointer
*/
// @lc code=start
/*
// 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 == nullptr){
return nullptr;
}
Node* temp = head;
while(temp != nullptr){
Node* temp1 = new Node(temp->val);
Node* temp2 = temp->next;
temp->next = temp1;
temp1->next = temp2;
temp = temp2;
}
temp = head;
while(temp != nullptr && temp->next != nullptr){
if(temp->random )
temp->next->random = temp->random->next;
temp = temp->next->next;
}
Node* odd = head;
Node* even = head->next;
Node* final1 = even;
while(odd->next != nullptr && even->next!=nullptr){
odd->next = even->next;
even->next = even->next->next;
odd=odd->next;
even=even->next;
}
if(odd){
odd->next = nullptr;
}
if(even->next){
even->next = nullptr;
}
return final1;
}
};
// @lc code=end