给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。
要求返回这个链表的深度拷贝。
-
思路分析:
这道题属于复杂链表的复制问题,若只是单纯的拷贝,那么遍历链表时就可以进行拷贝,但是这道题是每个节点还包含一个额外增加的随机指针,这就使问题变得有点复杂,具体解题思路分为三步来完成:
①复制结点:每遍历一个节点,就复制一个节点,并把复制的节点链在遍历节点的后面(不需要创建新的链表,在原链表上进行操作)
②置复制节点的Random:复制节点的Random是原节点的Random的下一个
③拆解链表:把拆下来的节点进行尾插,拆完同时恢复原链表,最后返回复制节点的头
-
具体代码如下:
/**
* Definition for singly-linked list with a random pointer.
* struct RandomListNode {
* int label;
* struct RandomListNode *next;
* struct RandomListNode *random;
* };
*/
struct RandomListNode *copyRandomList(struct RandomListNode *head) {
//1.复制结点
struct RandomListNode* cur=head;
while(cur)
{
struct RandomListNode* next=cur->next;
struct RandomListNode* copy=(struct RandomListNode*)malloc(sizeof(struct RandomListNode));
copy->label=cur->label;
copy->next=NULL;
cur->next=copy;
copy->next=next;
cur=next;
}
//2.置Random
cur=head;
while(cur)
{
struct RandomListNode* copy=cur->next;
if(cur->random)
{
copy->random=cur->random->next;
}
else
{
copy->random=NULL;
}
cur=copy->next;
}
//3.拆解链表
struct RandomListNode* newhead,*newtail;
newhead=newtail=NULL;
cur=head;
while(cur)
{
struct RandomListNode* copy=cur->next;
struct RandomListNode* next=copy->next;
if(newtail==NULL)
{
newhead=newtail=copy;
}
else
{
newtail->next=copy;
newtail=newtail->next;
}
cur->next=next;
cur=next;
}
return newhead;
}