自动秒收录

链表随机节点 (力扣 随机链表的复制 138.)


文章编号:1230 / 更新时间:2023-11-10 02:30:13 / 浏览:
138.

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;
}

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


相关标签: C语言

本文地址:https://www.0558.la/article/e907a123ccb3c3c0a615.html

上一篇:vuemobx上集vue模板语法...
下一篇:新注册的域名多久可以备案新注册的域名要如...

温馨提示

做上本站友情链接,在您站上点击一次,即可自动收录并自动排在本站第一位!
<a href="https://www.0558.la/" target="_blank">自动秒收录</a>