目录
题目:
解题思路:
实际上这道题中,拷贝链表并不难,就遍历一遍,按照原链表对应的值去malloc就好了,但难点就在于如何处理每个节点的random指针。
如何处理每个节点的random指针:
因为每个节点的random指针的指向是不确定的,所以我们可以在原链表中的两两节点中间加入我们的copy节点,通过原链表的相对位置来找到我们copy的链表中各个节点random指针对应的相对位置,如果原链表中的random指针指向不为NULL时,那么对应的copy节点的random指针就指向了源节点的random->next的位置。
解题代码:
struct Node* copyRandomList(struct Node* head) {
if(head==NULL)
return NULL;
struct Node* cur =head;
struct Node* copy=NULL;
//拷贝每个节点并嵌入到两个原节点中间
while(cur)
{
copy =(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
copy->next=cur->next;
cur->next=copy;
cur=copy->next;
}
cur=head;
//处理random指针
while(cur)
{
copy=cur->next;
if(cur->random)
copy->random=cur->random->next;
else
copy->random=NULL;
cur=copy->next;
}
//穿起copy节点
cur=head->next;
struct Node* newhead=(struct Node*)malloc(sizeof(struct Node));
struct Node* ptail=newhead;
while(cur)
{
ptail->next=cur;
ptail=ptail->next;
if(cur->next)
cur=cur->next->next;
else
cur=NULL;
}
return newhead->next;
}