欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > 力扣刷题-热题100题-第32题(c++、python)

力扣刷题-热题100题-第32题(c++、python)

2025/4/7 21:32:59 来源:https://blog.csdn.net/weixin_44505472/article/details/147024697  浏览:    关键词:力扣刷题-热题100题-第32题(c++、python)

138. 随机链表的复制 - 力扣(LeetCode)https://leetcode.cn/problems/copy-list-with-random-pointer/?envType=study-plan-v2&envId=top-100-liked

回溯哈希

c++利用unordered_set,python利用字典,创造哈希表来记录遍历过的随机链表,键作为原链表,值作为新链表。

遍历随机链表时,对于未遍历过的节点(不在哈希表中)创建新的节点并写入哈希表,然后调用自己创建next与random,若已遍历过(在哈希表内),就返回哈希表的值。

//c++
/*
// Definition for a Node.
class Node {
public:int val;Node* next;Node* random;Node(int _val) {val = _val;next = NULL;random = NULL;}
};
*/
class Solution 
{
private: std::unordered_map<Node*,Node*> v;
public:Node* copyRandomList(Node* head) {if(head==nullptr)   return nullptr;if(v.find(head)==v.end()){Node* a=new Node(head->val);v[head]=a;a->next=copyRandomList(head->next);a->random=copyRandomList(head->random);return a;}else    return v[head];}
};#python
"""
# Definition for a Node.
class Node:def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):self.val = int(x)self.next = nextself.random = random
"""
a={}
class Solution:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':if head==None:return Noneif head not in a:b=Node(head.val)a[head]=bb.next=self.copyRandomList(head.next)b.random=self.copyRandomList(head.random)return a[head]

迭代节点拆分

就是在原链表的每个元素后照葫芦画瓢创建一个新元素类比复制原元素的各个指向。

第一层循环创建元素并间隔插入原链表复制next

第二层循环将新元素的random指向原元素的random后的next

第三层循环将新元素从中拆下来得到新链表

//c++
/*
// Definition for a Node.
class Node {
public:int val;Node* next;Node* random;Node(int _val) {val = _val;next = NULL;random = NULL;}
};
*/
class Solution 
{
public:Node* copyRandomList(Node* head) {if(head==nullptr)   return nullptr;for(Node* i=head;i!=nullptr;i=i->next->next){Node* a=new Node(i->val);a->next=i->next;i->next=a;}for(Node* i=head;i!=nullptr;i=i->next->next){Node* a=i->next;a->random=(i->random==nullptr)?nullptr:i->random->next;}Node* ans=head->next;for(Node* i=head;i!=nullptr;i=i->next){Node* a=i->next;i->next=i->next->next;a->next=(a->next==nullptr)?nullptr:a->next->next;}return ans;}
};#python
"""
# Definition for a Node.
class Node:def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):self.val = int(x)self.next = nextself.random = random
"""
class Solution:def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':if head==None:return Nonei=headwhile i:a=Node(i.val)a.next=i.nexti.next=ai=i.next.nexti=headwhile i:a=i.nexta.random=i.random.next if i.random  else Nonei=i.next.nextans=head.nexti=headwhile i:a=i.nexti.next=i.next.nexta.next=a.next.next if a.next else Nonei=i.nextreturn ans

版权声明:

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

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

热搜词