-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLCloneWtithNextRandomPtr.cpp
More file actions
49 lines (44 loc) · 1.25 KB
/
LLCloneWtithNextRandomPtr.cpp
File metadata and controls
49 lines (44 loc) · 1.25 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
class Solution {
private:
void insertAtTail(Node* &head,Node *&tail, int val, Node* random){
Node* newNode = new Node(val);
if(head == NULL){
head = newNode;
tail = newNode;
newNode->random = random;
}
else{
tail->next = newNode;
tail = newNode;
newNode->random = random;
}
}
public:
Node *copyList(Node *head) {
Node* cloneHead = NULL;
Node* cloneTail = NULL;
Node* temp = head;
while(temp != NULL){
insertAtTail(cloneHead,cloneTail,temp->data,temp->random);
temp = temp->next;
}
/*
unordered_map<Node*, Node*> oldToNew;
Node* original = head;
Node* clone = cloneHead;
while(original != NULL && clone != NULL){
oldToNew[original] = clone;
original = original->next;
clone = clone->next;
}
original = head;
clone = cloneHead;
while(original != NULL){
clone->random = oldToNew[original->random];
original = original->next;
clone = clone->next;
}
*/
return cloneHead;
}
};