力扣 138. 随机链表的复制

简介: 利用C语言写出的解题思路

1.解题思路
在原先链表的每一个元素后面插入一个与前一个相同val的值的结点,然后由于是在原链表进行的操作,因此找每个random就变得很方便直接访问即可,此题目的精髓是cur1->random=p->random->next,看懂这串代码的话,这道题也就迎刃而解了.

2.代码实现



struct Node* copyRandomList(struct Node* head)
 { 
  struct Node* cur=head;
   while(cur)
   {   struct Node* next=cur->next;
       struct Node*p=( struct Node*)malloc(sizeof( struct Node));
       p->val=cur->val;
       p->next=next;
       cur->next=p;
       cur=next;
   }
 struct Node* p=head;
 while(p)
 { 
   struct Node* cur1=p->next;
   if(p->random==NULL)
   {
       cur1->random=NULL;
       p=cur1->next;
   }
else
{
   cur1->random=p->random->next;
   p=cur1->next;
}

 }
 struct Node*newnode=NULL;
   struct Node*tail=NULL;
 while(head)
 {
  if(tail==NULL)
  {
    tail=newnode=head->next;
    head=head->next->next;
  }
  else
  {
     tail->next=head->next;
     tail=head->next;
     head=head->next->next;
  }

 }
return newnode;
}

结尾:今天的分享到此结束,喜欢的朋友如果感觉有帮助可以点赞三连支持,咱们共同进步!

目录
相关文章
|
6天前
LeetCode链表hard 有思路?但写不出来?
LeetCode链表hard 有思路?但写不出来?
|
6天前
|
索引
每日一题:力扣328. 奇偶链表
每日一题:力扣328. 奇偶链表
14 4
|
6天前
leetcode代码记录(移除链表元素
leetcode代码记录(移除链表元素
11 0
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——反转链表
【每日一题】LeetCode——链表的中间结点
【每日一题】LeetCode——链表的中间结点
|
6天前
|
C++
[leetcode 链表] 反转链表 vs 链表相交
[leetcode 链表] 反转链表 vs 链表相交
|
6天前
【力扣】148. 排序链表
【力扣】148. 排序链表
|
6天前
|
索引
【力扣】142. 环形链表 II
【力扣】142. 环形链表 II
|
6天前
【力扣】19. 删除链表的倒数第 N 个结点
【力扣】19. 删除链表的倒数第 N 个结点
|
6天前
|
C语言 C++ 索引
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表
【力扣】141. 环形链表、160. 相交链表、206.反转链表、234. 回文链表