链表收尾(8.2)

编程入门 行业动态 更新时间:2024-10-18 18:14:11

链表<a href=https://www.elefans.com/category/jswz/34/1758081.html style=收尾(8.2)"/>

链表收尾(8.2)

 例题解析

138. 随机链表的复制 - 力扣(LeetCode)

1.拷贝节点插入原节点的后面(核心)

这样做的目的是方便找 random 节点,知道原节点可以找 random,知道上一个 random 可以找下一个 random 。

    struct Node* cur=head;while(cur){//通过一前一后两个指针来插入节点struct Node* next=cur->next;struct Node* copy=(struct Node*)malloc(sizeof(struct Node));copy->val=cur->val;//链接cur->next=copy;copy->next=next;//cur移动cur=next;}

2.放置每个拷贝节点的 random 

我们可以通过原节点的 random 轻松找到拷贝的 random 

    cur=head;//放置拷贝节点的randomwhile(cur){//从cur的下一个节点开始遍历struct Node* copy=cur->next;//如果原节点的random为空,拷贝节点的random也为空if(cur->random==NULL){copy->random=NULL;}else//否则拷贝节点的random等于原节点的random的拷贝节点{copy->random=cur->random->next;}//cur后移动一位cur=copy->next;}

3.将拷贝节点与原链表解开,尾插到一起,并恢复原链表的链接

    cur=head;    
//创建新链表的头尾节点便于插入struct Node* copyhead=NULL,*copytail=NULL;while(cur){struct Node* copy=cur->next;struct Node* next=copy->next;//copy节点尾插到新链表if(copyhead==NULL){copy= copyhead=copytail;}else{copytail->next=copy;copytail=copytail->next;}//恢复原节点cur->next=next;cur=next;}

完整代码:

/*** Definition for a Node.* struct Node {*     int val;*     struct Node *next;*     struct Node *random;* };*/struct Node* copyRandomList(struct Node* head) {//拷贝节点到原节点的后面struct Node* cur=head;while(cur){//通过一前一后两个指针来插入节点struct Node* next=cur->next;struct Node* copy=(struct Node*)malloc(sizeof(struct Node));copy->val=cur->val;//链接cur->next=copy;copy->next=next;//cur移动cur=next;}cur=head;//放置拷贝节点的randomwhile(cur){//从cur的下一个节点开始遍历struct Node* copy=cur->next;//如果原节点的random为空,拷贝节点的random也为空if(cur->random==NULL){copy->random=NULL;}else//否则拷贝节点的random等于原节点的random的拷贝节点{copy->random=cur->random->next;}//cur后移动一位cur=copy->next;}cur=head;//创建新链表的头尾节点便于插入struct Node* copyhead=NULL,*copytail=NULL;while(cur){struct Node* copy=cur->next;struct Node* next=copy->next;//copy节点尾插到新链表if(copytail==NULL){copyhead=copytail=copy;}else{copytail->next=copy;copytail=copytail->next;}//恢复原节点cur->next=next;cur=next;}return copyhead;
}

4.顺序表和链表的区别

拓展学习:

更多推荐

链表收尾(8.2)

本文发布于:2023-12-05 18:48:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1665006.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:收尾   链表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!