题海拾贝:力扣 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;
}

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

相关推荐
酌量13 分钟前
基于3D激光点云的障碍物检测与跟踪---(3)基于匈牙利算法的障碍物跟踪
学习·算法·机器人·匈牙利算法·障碍物跟踪
.ZGR.33 分钟前
蓝桥杯高校新生编程赛第一场题解——Java
java·算法·蓝桥杯
自由生长202437 分钟前
数据结构科普-红黑树
算法
每天进步一点点dlb1 小时前
JVM中的垃圾回收算法和垃圾回收器
jvm·算法
我爱鸢尾花1 小时前
CNN基础理论讲解及Python代码复现
人工智能·python·深度学习·神经网络·算法·机器学习·cnn
大数据张老师1 小时前
数据结构——二叉搜索树
数据结构·算法·二叉搜索树·查找·关键路径
攻城狮CSU2 小时前
类型转换汇总 之C#
java·算法·c#
小老鼠不吃猫2 小时前
C++ STL <algorithm>中泛型算法:查找、排序、修改、统计、生成
c++·算法·排序算法
白杆杆红伞伞2 小时前
01_svm_二分类
算法·支持向量机·分类
isyoungboy2 小时前
使用SVM构建光照鲁棒的颜色分类器:从特征提取到SVM
算法·机器学习·支持向量机