LeetCode 138. Copy List with Random Pointer [Python]

本文介绍了一种解决LeetCode上复杂链表复制问题的方法,该链表节点包含一个额外的随机指针。通过使用哈希表,文章详细阐述了如何创建链表的深拷贝,包括两步:首先复制所有节点到哈希表,然后根据原始链表建立关系。

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

LeetCode link: https://leetcode.com/problems/copy-list-with-random-pointer/

Question Description:

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.
The Linked List is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val
  • random_index: the index of the node (range from 0 to n-1) where random pointer points to, or null if it does not point to any node.
Method:
  1. Create hash table, copy every node to hash table.
  2. Build relationship according to original linked list.
Code:
class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if head is None:
            return None
        
        nodeDict = dict()
        
        # First loop to copy all node
        pointer = head
        while pointer:
            nodeDict[pointer] = Node(pointer.val, None, None)
            pointer = pointer.next
        
        # Second loop to copy relationship
        pointer = head
        while pointer:
            if pointer.next:
                nodeDict[pointer].next = nodeDict[pointer.next]
            if pointer.random:
                nodeDict[pointer].random = nodeDict[pointer.random]
            pointer = pointer.next
        
        return nodeDict[head]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值