思路:
复制小弟和random,在每个p节点的后面,最后再拆分。
代码:
/*
// 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) {
//复制小弟
for(auto p = head; p; p = p->next->next){
auto q = new Node(p->val);
q->next = p->next;
p->next = q;
}
//复制random
for(auto p = head; p; p = p->next->next){
if(p->random){
p->next->random = p->random->next;
}
}
//拆分
auto dummy = new Node(-1);
auto cur = dummy;
for(auto p = head; p; p = p->next){
cur = cur->next = p->next;
p->next = p->next->next;
}
return dummy->next;
}
};
评论区