Skip to content

Commit 28c16f3

Browse files
committed
copy_list_with_random_pointer
1 parent 75159d2 commit 28c16f3

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
121121
#### [135. candy](https://github.com/hitzzc/go-leetcode/tree/master/candy)
122122
#### [136. single number](https://github.com/hitzzc/go-leetcode/tree/master/single_number)
123123
#### [137. single number II](https://github.com/hitzzc/go-leetcode/tree/master/single_number_II)
124+
#### [138. copy_list_with_random_pointer](https://github.com/hitzzc/go-leetcode/tree/master/copy_list_with_random_pointer)
124125

125126

126127

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <unordered_map>
2+
using namespace std;
3+
4+
struct RandomListNode {
5+
int label;
6+
RandomListNode *next, *random;
7+
RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
8+
};
9+
10+
class Solution {
11+
public:
12+
RandomListNode *copyRandomList(RandomListNode *head) {
13+
if (head==NULL) return NULL;
14+
auto fake = new RandomListNode(0);
15+
unordered_map<RandomListNode*, RandomListNode*> mapping;
16+
auto ptr = head;
17+
auto pre_copy = fake;
18+
while (ptr!=NULL){
19+
RandomListNode* copy_node;
20+
if (mapping.find(ptr)!=mapping.end())
21+
copy_node = mapping[ptr];
22+
else{
23+
copy_node = new RandomListNode(ptr->label);
24+
mapping[ptr] = copy_node;
25+
}
26+
pre_copy->next = copy_node;
27+
pre_copy = pre_copy->next;
28+
29+
if (ptr->random!=NULL){
30+
RandomListNode* copy_node_random;
31+
if (mapping.find(ptr->random)!=mapping.end()){
32+
copy_node_random = mapping[ptr->random];
33+
}
34+
else{
35+
copy_node_random = new RandomListNode(ptr->random->label);
36+
mapping[ptr->random] = copy_node_random;
37+
}
38+
copy_node->random = copy_node_random;
39+
}
40+
ptr = ptr->next;
41+
}
42+
return fake->next;
43+
}
44+
};

0 commit comments

Comments
 (0)