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

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

相关推荐
Hcoco_me3 小时前
大模型面试题17:PCA算法详解及入门实操
算法
跨境卫士苏苏3 小时前
亚马逊AI广告革命:告别“猜心”,迎接“共创”时代
大数据·人工智能·算法·亚马逊·防关联
程序员小白条4 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
云雾J视界4 小时前
当算法试图解决一切:技术解决方案主义的诱惑与陷阱
算法·google·bert·transformer·attention·算法治理
Xの哲學4 小时前
Linux Miscdevice深度剖析:从原理到实战的完整指南
linux·服务器·算法·架构·边缘计算
夏乌_Wx5 小时前
练题100天——DAY23:存在重复元素Ⅰ Ⅱ+两数之和
数据结构·算法·leetcode
立志成为大牛的小牛5 小时前
数据结构——五十六、排序的基本概念(王道408)
开发语言·数据结构·程序人生·算法
a努力。5 小时前
Redis Java 开发系列#2 数据结构
java·数据结构·redis
沿着路走到底6 小时前
将数组倒序,不能采用reverse,算法复杂度最低
算法