题海拾贝:力扣 138.随机链表的复制

Hello大家好!很高兴我们又见面啦!给生活添点passion,开始今天的编程之路!

我的博客: <但凡.

我的专栏: 《编程之路》《数据结构与算法之美》《题海拾贝》

欢迎点赞,关注!

1、题目

题目链接:138. 随机链表的复制 - 力扣(LeetCode)

题解:

这个题的解答方法和平常的不太一样,我们需要先复制每个节点然后插入到原链表中,这样来设置每个新节点的randam节点。需要注意的是,我们需要处理特殊情况,也就是链表为NULL的情况。

cpp 复制代码
/**
 * Definition for a Node.
 * struct Node {
 *     int val;
 *     struct Node *next;
 *     struct Node *random;
 * };
 */
 struct Node* buynode(int x)
 {
    struct Node* newnode=(struct Node*)malloc(sizeof(struct Node));
    newnode->val=x;
    newnode->next=NULL;
    newnode->random=NULL;
    return newnode;
 }
 void test(struct Node* head)
 {
    struct Node* cur=head;
    while(cur)
    {
        struct Node* newnode=buynode(cur->val);
    struct Node* curnext=cur->next;
    cur->next=newnode;
    newnode->next=curnext;
    cur=curnext;
    }
 }
 void setrandom(struct Node* head)
 {
    struct Node* cur=head;
    while(cur)
    {
        struct Node* Nnext=cur->next;
        if(cur->random)
        {Nnext->random=cur->random->next;}
        //注意if条件。如果random是NULL的话,cur->random->next会报错
        struct Node* curnext=Nnext->next;
        cur=curnext;
    }
 }
 struct Node* SetNewList(struct Node* head)
 {
    struct Node* cur=head;
    struct Node* newhead=head->next;
    struct Node* newcur=head->next;
    struct Node*curnext=newcur->next;
    while(curnext)
    {
        newcur->next=curnext->next;
        newcur=newcur->next;
        curnext=newcur->next;
    }
    return newhead;
 }
struct Node* copyRandomList(struct Node* head) {
   //处理特殊情况------------------------------------------------
   if(head==NULL)
   {
    return head;
   }
   test(head);
   setrandom(head);
   struct Node* newhead=SetNewList(head);
   return newhead;
}

好了,今天的内容就分享到这,我们下期再见!

相关推荐
努力学习的小廉15 分钟前
【C++】 —— 笔试刷题day_21
开发语言·c++·算法
周杰伦_Jay40 分钟前
continue插件实现IDEA接入本地离线部署的deepseek等大模型
java·数据结构·ide·人工智能·算法·数据挖掘·intellij-idea
江沉晚呤时43 分钟前
深入了解递归、堆与栈:C#中的内存管理与函数调用
java·jvm·算法
愚润求学1 小时前
【专题刷题】二分查找(一):深度解刨二分思想和二分模板
开发语言·c++·笔记·leetcode·刷题
岩中竹1 小时前
力扣热题100题解(c++)—矩阵
数据结构·c++·程序人生·算法·leetcode·矩阵
啊阿狸不会拉杆1 小时前
数据结构-图
java·c语言·数据结构·c++·python·算法·图论
稻草猫.2 小时前
【Java 数据结构】泛型
java·数据结构
愚润求学2 小时前
【数据结构】哈希表
数据结构·c++·笔记·散列表
SophiaSSSSS3 小时前
无标注文本的行业划分(行业分类)算法 —— 无监督或自监督学习
学习·算法·分类
丶Darling.3 小时前
26考研 | 王道 | 数据结构 | 第七章 查找
前端·数据结构·考研