【138. 复制带随机指针的链表】


一、题目描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
题目链接


二、提供方便走读代码的图

在这里插入图片描述


三、题目代码

/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */

struct Node* copyRandomList(struct Node* head) {
	struct Node* cur = head;
    struct Node* copy;
    //复制节点,插入到原节点和下个节点之间
    while(cur)
    {
        copy=(struct Node*)malloc(sizeof(struct Node));
        copy->val=cur->val;
        copy->next=cur->next;
        cur->next=copy;
        cur=copy->next;
    }
    //根据原节点random,处理复制节点的random
    cur = head;
    while(cur)
    {
        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* newtail=NULL;
    while(cur)
    {
        struct Node* next=cur->next->next;
        if(newhead==NULL)
        {
            newhead= newtail=cur->next;
        }
        else
        {
             newtail->next=cur->next;
             newtail=cur->next;
        }
        cur->next=next;
        cur=next;

    }
    return newhead;
}

以上是本篇文章的全部内容,如果文章有错误或者有看不懂的地方,多和喵博主交流。互相学习互相进步。如果这篇文章对你有帮助,可以给喵博主一个关注,你们的支持是我最大的动力。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值