forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path138.cpp
More file actions
46 lines (44 loc) · 1.05 KB
/
138.cpp
File metadata and controls
46 lines (44 loc) · 1.05 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
/*
// 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 head;
Node *orighead=head;
while(head){
Node *temp=new Node(head->val);
temp->next=head->next;
head->next=temp;
head=temp->next;
}
head=orighead;
Node *copy=head->next;
while(head){
copy->random=head->random? head->random->next : head->random;
copy=copy->next? copy->next->next: NULL;
head=head->next->next? head->next->next: NULL;
}
head=orighead;
copy=head->next;
Node *copyhead=copy;
while(head){
head->next=head->next? head->next->next: NULL;
head=head->next;
copy->next=copy->next? copy->next->next: NULL;
copy=copy->next;
}
return copyhead;
}
};