LeetCode0138. Copy List with Random Pointer

本文介绍了一种复杂链表结构的深拷贝方法,该链表每个节点包含一个额外的随机指针。通过使用字典或collections.defaultdict(),可以有效地复制链表并正确设置随机指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

Input:
{"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1}

Explanation:
Node 1's value is 1, both of its next and random pointer points to Node 2.
Node 2's value is 2, its next pointer points to null and its random pointer points to itself.

一开始没太理解这道题的意思,又看了看deepcopy的意思https://blog.youkuaiyun.com/AIpush/article/details/102595709

其实就是再复制一遍这个链表,关键在于这个random是随机链接一个ListNode的,怎么去找到这个ListNode。

这里就要用dict()的get操作了

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, next, random):
        self.val = val
        self.next = next
        self.random = random
"""
class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        dic = dict()
        
        cur = head
        while cur:
            dic[cur] = Node(cur.val, None, None)
            cur = cur.next
        
        cur=head
        while cur:
            if cur.next:
                dic[cur].next = dic.get(cur.next)
            if cur.random:
                dic[cur].random = dic.get(cur.random)
            cur = cur.next
            
        return dic.get(head)

或者使用python的collections.defaultdict()方法,参考https://blog.youkuaiyun.com/yangsong95/article/details/82319675

这样就可以只用一个循环解决

class Solution(object):
    def copyRandomList(self, head):
        """
        :type head: Node
        :rtype: Node
        """
        import collections as c
        
        dic = c.defaultdict(lambda:Node(0,None,None))
        
        dic[None]=None
        
        p=head
        while p:
            dic[p].val = p.val
            dic[p].next = dic[p.next]
            dic[p].random = dic[p.random]
            p=p.next
        return dic[head]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值