力扣 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天前
【力扣】-- 移除链表元素
【力扣】-- 移除链表元素
16 1
|
13天前
Leetcode第21题(合并两个有序链表)
这篇文章介绍了如何使用非递归和递归方法解决LeetCode第21题,即合并两个有序链表的问题。
37 0
Leetcode第21题(合并两个有序链表)
|
15天前
|
算法
【链表】算法题(二) ----- 力扣/牛客
【链表】算法题(二) ----- 力扣/牛客
|
13天前
LeetCode第二十四题(两两交换链表中的节点)
这篇文章介绍了LeetCode第24题的解法,即如何通过使用三个指针(preNode, curNode, curNextNode)来两两交换链表中的节点,并提供了详细的代码实现。
12 0
LeetCode第二十四题(两两交换链表中的节点)
|
13天前
Leetcode第十九题(删除链表的倒数第N个节点)
LeetCode第19题要求删除链表的倒数第N个节点,可以通过快慢指针法在一次遍历中实现。
32 0
Leetcode第十九题(删除链表的倒数第N个节点)
|
13天前
|
索引
力扣(LeetCode)数据结构练习题(3)------链表
力扣(LeetCode)数据结构练习题(3)------链表
27 0
|
13天前
【LeetCode 10】142. 环形链表 II
【LeetCode 10】142. 环形链表 II
16 0
|
13天前
【LeetCode 09】19 删除链表的倒数第 N 个结点
【LeetCode 09】19 删除链表的倒数第 N 个结点
12 0
|
13天前
【LeetCode 08】206 反转链表
【LeetCode 08】206 反转链表
11 0
|
13天前
【LeetCode 06】203.移除链表元素
【LeetCode 06】203.移除链表元素
26 0