随机链表的复制

题目描述

给你一个长度为n的链表,每个节点包含一个额外增加的随机指针random,该指针可以指向链表中的任何节点或空节点。构造这个链表的深拷贝。 深拷贝应该正好由n全新节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的next指针和random指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 

随机链表的复制_第1张图片

 随机链表的复制_第2张图片

 解题思路

这道题可谓是难倒了博主很长时间,经过长时间琢磨之后,现写出这道题的一种解题思路:

随机链表的复制_第3张图片

以这样的一个例子为例,第一步,先拷贝结点插入在尾节点后面,如下图,

随机链表的复制_第4张图片

struct Node* cur=head;
while(cur)
{
    struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
    copy->val=cur->val;
    copy->next=cur->next;
    cur->next=copy;

    cur=cur->next->next;
}

第二步,处理copy结点的random,让copy结点的random指向其前一个结点所指向的下一个结点的下一个copy结点。

随机链表的复制_第5张图片

cur=head;
while(cur)
{
    struct Node* copy=cur->next;
    if(cur->random == NULL)
    {
        copy->random=NULL;
    }
    else
    {
        copy->random=cur->random->next;

    }
    cur=copy->next; 
}

 第三步,copy结点解下来尾插。

随机链表的复制_第6张图片

    cur=head;
    struct Node* newhead=NULL;
    struct Node* tail=NULL;
    while(cur)
    {
        struct Node* copy=cur->next;
        if(tail == NULL)
        {
            newhead=tail=copy;
        }
        else
        {
            tail->next=copy;
            tail=tail->next;
        }
        cur->next=copy->next;
        cur=copy->next;
    }

这里提供一下这道题的完整代码:

struct Node* copyRandomList(struct Node* head) 
{
    struct Node* cur=head;
    while(cur)
    {
        struct Node* copy=(struct Node*)malloc(sizeof(struct Node));
        copy->val=cur->val;
        copy->next=cur->next;
        cur->next=copy;

        cur=cur->next->next;
    }

    cur=head;
    while(cur)
    {
        struct Node* 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* tail=NULL;
    while(cur)
    {
        struct Node* copy=cur->next;
        if(tail == NULL)
        {
            newhead=tail=copy;
        }
        else
        {
            tail->next=copy;
            tail=tail->next;
        }
        cur->next=copy->next;
        cur=copy->next;
    }

    return newhead;	
}

你可能感兴趣的:(数据结构经典习题,链表,数据结构)