随机链表的复制

题目描述

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

 

 解题思路

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

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

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结点。

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结点解下来尾插。

    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;	
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值