题目描述
思路分析
链表操作练习
把每个节点的复制节点加到对应节点后边,这样可以节省一个哈希表
代码实现
/*
// 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;
}
for(auto p=head;p;p=p->next->next){
if(p->random){
p->next->random=p->random->next;
}
}
auto dummy=new Node(-1);
auto tail=dummy;
for(auto p=head;p;p=p->next){
auto q=p->next;
tail=tail->next=q;
p->next=q->next;
}
return dummy->next;
}
};