欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 旅游 > 题海拾贝:力扣 138.随机链表的复制

题海拾贝:力扣 138.随机链表的复制

2025/4/23 7:35:33 来源:https://blog.csdn.net/2401_87995839/article/details/145231173  浏览:    关键词:题海拾贝:力扣 138.随机链表的复制

         Hello大家好!很高兴我们又见面啦!给生活添点passion,开始今天的编程之路!

我的博客:<但凡.

我的专栏:《编程之路》、《数据结构与算法之美》、《题海拾贝》

欢迎点赞,关注!

1、题目 

题目链接:138. 随机链表的复制 - 力扣(LeetCode) 

题解:

        这个题的解答方法和平常的不太一样,我们需要先复制每个节点然后插入到原链表中,这样来设置每个新节点的randam节点。需要注意的是,我们需要处理特殊情况,也就是链表为NULL的情况。

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

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

 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词