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

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

相关推荐
wzdark3 小时前
基于堆的优先队列实现原理与复杂度分析4
算法
彧azz4 小时前
图的存储结构详解:邻接矩阵的原理、实现与应用
开发语言·数据结构·学习·php
老王熬夜敲代码5 小时前
BLAKE3:最快的密码学哈希函数
算法·密码学·哈希算法
hansang_IR5 小时前
【题解】P4460 [CQOI2018] 解锁屏幕
c++·算法
见闻小天地5 小时前
简博斯JG-C系列彩色激光同轴位移计:摄像头模组对位与行程测量的技术价值观察
人工智能·算法
葫三生6 小时前
《论三生原理》神话学构想与“神话历史”理论、《古史中的神话》思路异同?
大数据·人工智能·科技·深度学习·算法
liliangcsdn6 小时前
因子分析指标概念与示例
算法·机器学习
SupL!7 小时前
LoftQ原理
算法
Navigator_Z9 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟9 小时前
力扣100——双指针
算法·leetcode