https://leetcode.cn/problems/copy-list-with-random-pointer/
这道题重点在于对指针的把握,理解好指针的指向,就不难了
分下面三步解决
代码如下:
struct Node* copyRandomList(struct Node* head) {
struct Node*cur=head;
//拷贝原链表的值
while(cur)
{
struct Node*Next=(struct Node*)malloc(sizeof(struct Node));
Next->val=cur->val;
Next->next=cur->next;
cur->next=Next;
cur=Next->next;
}
//处理random
cur=head;
while(cur)
{
struct Node*pnext=cur->next;
if(cur->random==NULL)
{
pnext->random=NULL;
}
else
{
pnext->random=cur->random->next;
}
cur=pnext->next;
}
//取出next,直接拿下来即可,不需要开辟额外的空间
cur=head;
struct Node*new_head=NULL,*new_tail=NULL;
while(cur)
{
if(new_head==NULL)
{
new_head=new_tail=cur->next;
}
else
{
new_tail->next=cur->next;
new_tail=cur->next;
}
cur=cur->next->next;
}
return new_head;
}