-
Notifications
You must be signed in to change notification settings - Fork 0
/
138.复制带随机指针的链表.cpp
67 lines (60 loc) · 1.29 KB
/
138.复制带随机指针的链表.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* @lc app=leetcode.cn id=138 lang=cpp
*
* [138] 复制带随机指针的链表
*/
// @lc code=start
/*
// 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 == nullptr) return nullptr;
auto* h = head->next;
auto* result = new Node(head->val);
auto* r = result;
while(h != nullptr){
auto* t = new Node(h->val);
r->next = t;
r = t;
h = h->next;
}
h = head;
r = result;
while(h != nullptr){
if(h->random != nullptr){
auto cnt = distance(head, h->random);
auto* t = result;
for(int i = 0; i < cnt; i++){
t = t->next;
}
r->random = t;
}
h = h->next;
r = r->next;
}
return result;
}
private:
int distance(Node* head, Node* target) const{
int result = 0;
while(head != target){
result++;
head = head->next;
}
return result;
}
};
// @lc code=end