-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path138. Copy List with Random Pointer.cpp
52 lines (48 loc) · 1.18 KB
/
138. Copy List with Random Pointer.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
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
using namespace std;
// 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==NULL) return NULL;
map<Node*,Node*> mp;
Node *copyHead=new Node(head->val);
Node *tmpCopyNode=copyHead;
Node *tmpNode=head;
int cnt=0;
//copy next pointer
while(tmpNode!=NULL){
mp.insert(make_pair(tmpNode,tmpCopyNode));
tmpNode=tmpNode->next;
if(tmpNode==NULL) break;
tmpCopyNode->next=new Node(tmpNode->val);
tmpCopyNode=tmpCopyNode->next;
}
tmpNode=head;
tmpCopyNode=copyHead;
//copy random pointer
while(tmpNode!=NULL){
if(tmpNode->random!=NULL){
tmpCopyNode->random=mp[tmpNode->random];
}
tmpNode=tmpNode->next;
tmpCopyNode=tmpCopyNode->next;
}
return copyHead;
}
};