一、题目描述
二、提供方便走读代码的图
三、题目代码
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
struct Node* cur = head;
struct Node* copy;
//复制节点,插入到原节点和下个节点之间
while(cur)
{
copy=(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
copy->next=cur->next;
cur->next=copy;
cur=copy->next;
}
//根据原节点random,处理复制节点的random
cur = head;
while(cur)
{
copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
cur=copy->next;
}
//复制节点解下来链接成一个新链表,恢复原链表链接关系
cur = head;
struct Node* newhead=NULL;
struct Node* newtail=NULL;
while(cur)
{
struct Node* next=cur->next->next;
if(newhead==NULL)
{
newhead= newtail=cur->next;
}
else
{
newtail->next=cur->next;
newtail=cur->next;
}
cur->next=next;
cur=next;
}
return newhead;
}
以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。