forked from PRAN20/Top-Interview-Questions-LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy_list.cpp
32 lines (28 loc) · 780 Bytes
/
Copy_list.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
class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return NULL;
Node* temp = head;
while(temp){
Node* node = new Node(temp->val);
node->next = temp->next;
temp->next = node;
temp = node->next;
}
temp = head;
while(temp){
temp->next->random = (temp->random)?temp->random->next:NULL;
temp = temp->next->next;
}
Node* ans = head->next;
temp = head->next;
while(head){
head->next = temp->next;
head = head->next;
if(!head) break;
temp->next = head->next;
temp = temp->next;
}
return ans;
}
};