封面

LeetCode 题解 · 随机链表的复制

笔记日期
# LeetCode
# Python
# 哈希表

普通链表可以边走边复制。麻烦的是 random 指针会跳到后面,甚至指向自己;第一次遇见它时,目的节点的副本可能还没建好。把“建节点”和“连接”拆成两趟,顺序就清楚了。

设 A、B 的值都是 7,A.random 指向 B,B.random 指回 A。第一趟建出 A′ 和 B′,第二趟把 A′.random 接到 B′。字典以原节点对象为键;只用数值 7 做键会把两个节点混为一个。

class Solution:
    def copyRandomList(self, head):
        copies = {None: None}
        node = head
        while node:
            copies[node] = Node(node.val)
            node = node.next
        node = head
        while node:
            clone = copies[node]
            clone.next = copies[node.next]
            clone.random = copies[node.random]
            node = node.next
        return copies[head]

空指针在映射里对应空指针,因此空链、空 random 和自环都能照常处理。两次沿 next 遍历,总时间 O(n),映射额外占 O(n)。Node 由题目提供。

LeetCode 第 138 题

返回 LeetCode 题单 →