思路:
可以不开哈希表,把映射关系用其他方式来处理,让小弟跟在自己大哥后面。
最后再拆分链表
代码:
/*
// 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), cur = dummy;
for (auto p = head; p; p = p->next) {
auto q = p->next;
cur = cur->next = q;
p->next = q->next;
}
return dummy->next;
}
};
评论区