复杂链表的复制
优质
小牛编辑
119浏览
2023-12-01
class Solution {
public:
RandomListNode* Clone(RandomListNode* pHead)
{
if(pHead==nullptr) return pHead;
//复制每一个节点并插入在之后
RandomListNode * currentNode=pHead;
while(currentNode)
{
RandomListNode *newNode=new RandomListNode(currentNode->label);
newNode->next=currentNode->next;
currentNode->next=newNode;
currentNode=newNode->next;
}
//插入随机指针
currentNode=pHead;
RandomListNode *p;
while(currentNode)
{
p=currentNode->next;
if(currentNode->random)
{
p->random=currentNode->random->next;
}
currentNode=p->next;
}
//拆分链表
currentNode=pHead;
RandomListNode *tmp;
RandomListNode *rHead=currentNode->next;
while(currentNode->next)
{
tmp=currentNode->next;
currentNode->next=tmp->next;
currentNode=tmp;
}
return rHead;
}
};