题目
代码
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node() {}
Node(int _val, Node* _next, Node* _random) {
val = _val;
next = _next;
random = _random;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head==nullptr)
return nullptr;
auto originPtr=head;
Node* newHead=new Node(head->val,nullptr,nullptr);
auto ptr=newHead;
//先深拷贝结点
while(originPtr->next!=nullptr)
{
auto node=new Node(originPtr->next->val,nullptr,nullptr);
ptr->next=node;
ptr=ptr->next;
originPtr=originPtr->next;
}
originPtr=head;
ptr=newHead;
//复制随机指针
while(originPtr!=nullptr)
{
//当前结点有随机指针
if(originPtr->random!=nullptr)
{
auto tempOld=head;
auto tempNew=newHead;
while(tempOld!=nullptr)
{
if(tempOld==originPtr->random)
{
ptr->random=tempNew;
break;
}else
{
tempOld=tempOld->next;
tempNew=tempNew->next;
}
}
}
originPtr=originPtr->next;
ptr=ptr->next;
}
return newHead;
}
};