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

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

相关推荐
GG不是gg2 分钟前
排序算法之基础排序:冒泡,选择,插入排序详解
数据结构·算法·青少年编程·排序算法
随意起个昵称25 分钟前
【双指针】供暖器
算法
倒霉蛋小马28 分钟前
最小二乘法拟合直线,用线性回归法、梯度下降法实现
算法·最小二乘法·直线
codists1 小时前
《算法导论(第4版)》阅读笔记:p82-p82
算法
埃菲尔铁塔_CV算法1 小时前
深度学习驱动下的目标检测技术:原理、算法与应用创新
深度学习·算法·目标检测
Dream it possible!1 小时前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
float_com1 小时前
【背包dp-----分组背包】------(标准的分组背包【可以不装满的 最大价值】)
算法·动态规划
丶Darling.2 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
L_cl3 小时前
【Python 算法零基础 3.递推】
算法
int型码农3 小时前
数据结构第七章(四)-B树和B+树
数据结构·b树·算法·b+树