qidao123.com ToB IT社区-企服评测·应用市场

标题: 【数据结构与算法】leetcode随机链表的复制 深度讲解 [打印本页]

作者: 笑看天下无敌手    时间: 2025-3-20 01:24
标题: 【数据结构与算法】leetcode随机链表的复制 深度讲解
随机链表的复制

   小编个人主页详情<—请点击
小编个人gitee代码仓库<—请点击
数据结构与算法系列专栏<—请点击

  
  
一、标题解读

   查看原题请点击<—


  
二、解题思路

在了解标题要求之后,那么我们就可以来举行构思这个标题的思路了
三种猜想思路

思路一

思路二

思路三

   

     那么有没有一种方法时间复杂度为O(N)呢?有的有的,请看小编下面文章,真正的思路讲解
  真正的解题思路

1.构建重组链表


2.寻找复制链表的随机指针并赋值


3.复原随机链表和复制链表

   

    好了到这里,小编信赖屏幕眼前的你已经对这个标题的思路大要了解了,点击链接实验做一下吧查看原题请点击<—
  
三、编写代码


下面即为该题的代码
  1. /**
  2. * Definition for a Node.
  3. * struct Node {
  4. *     int val;
  5. *     struct Node *next;
  6. *     struct Node *random;
  7. * };
  8. */
  9. struct Node* copyRandomList(struct Node* head) {
  10.     //构造复杂链表链接到随机链表节点后面
  11.         struct Node* cur=head;
  12.     while(cur)
  13.     {
  14.         struct Node* newnode=(struct Node*)malloc(sizeof(struct Node));
  15.         struct Node* next=cur->next;
  16.         newnode->val=cur->val;
  17.         //链接
  18.         cur->next=newnode;
  19.         newnode->next=next;
  20.         //迭代
  21.         cur=next;
  22.     }
  23.     //赋值随机指针
  24.     cur=head;
  25.     while(cur)
  26.     {
  27.         struct Node* copy=cur->next;
  28.         //链接
  29.         if(cur->random==NULL)
  30.         {
  31.             copy->random=NULL;
  32.         }
  33.         else
  34.         {
  35.             copy->random=cur->random->next;
  36.         }
  37.         //迭代
  38.         cur=copy->next;
  39.     }
  40.     //复原
  41.     struct Node* newhead,*tail;
  42.     newhead=tail=NULL;
  43.     cur=head;
  44.     while(cur)
  45.     {
  46.         struct Node* copy=cur->next;
  47.         struct Node* next=copy->next;//对copy和next根据cur进行初始化
  48.         cur->next=next;
  49.         if(newhead==NULL)
  50.         {
  51.             newhead=tail=copy;
  52.         }
  53.         else
  54.         {
  55.             tail->next=copy;
  56.             tail=copy;
  57.         }
  58.         cur=next;
  59.     }
  60.     return newhead;
  61. }
复制代码
总结

   以上就是今天的博客内容啦,水滴石穿,坚持就是胜利,读者朋侪们可以点个关注
点赞收藏加关注,关注小编的后续更新!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 qidao123.com ToB IT社区-企服评测·应用市场 (https://dis.qidao123.com/) Powered by Discuz! X3.5