⚡Flashcard Drill➔
NeetCode #324LC-138MediumLinked ListNC 150NC 250
← Back to All Problems

#324 · #138 · Copy List with Random Pointer(复制带随机指针的链表)

📌 Problem Statement & Constraints

A linked list has nodes with an extra random pointer that may point to any node or None. Return a deep copy of the list: new nodes, with next and random pointers reproducing the original structure. Constraints: 0 <= n <= 1000.

💡 Core Algorithmic Approaches

  1. First pass: create a copy of every node and store the mapping original -> copy in a hash map.
  2. Second pass: wire up next and random using the map.
  3. Two passes avoid the interleaving trick (which is O(1) space but harder to get right).
  4. The map is the key: without it, resolving a random pointer would require a search.

💻 Benchmark Python3 Implementation

class Solution:
    def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
        if not head:
            return None
        # pass 1: copy every node, remember the mapping
        mapping = {}
        cur = head
        while cur:
            mapping[cur] = Node(cur.val)
            cur = cur.next
        # pass 2: wire next and random
        cur = head
        while cur:
            mapping[cur].next = mapping.get(cur.next)      # None-safe
            mapping[cur].random = mapping.get(cur.random)
            cur = cur.next
        return mapping[head]

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): two passes with O(1) map operations.
💾 Space Complexity
O(n) for the mapping. The interleaving variant achieves O(1) extra space by weaving the copies into the original list.

⚠️ Interview Pitfalls & Follow-ups

  • Using mapping[cur.next] instead of .get(): a None key would raise a KeyError.
  • Copying only the values: the random pointers must reproduce the structure, which requires the node mapping.
  • Assuming random never points backwards: it can point to any node, including earlier ones -- which is exactly why the map is built first.
  • Trying to deep-copy with copy.deepcopy: it would follow the pointers and copy the whole graph, but the resulting node types and structure are not guaranteed to match the expected interface.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Linked List Problems

中文速览与面试要点

复制带随机指针的链表

给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random,该指针可以指向链表中的任何节点或空节点。构造这个链表的 深拷贝 。深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。 复制链表中的指针都不应指向原链表中的节点 。约束:0 ≤ n ≤ 1000;-10^4 ≤ Node.val ≤ 10^4;Node.random 为 null 或指向链表中的节点。

核心要点

  • 交错插入 + 拆分(O(1) 额外空间,推荐) :① 在每个原节点后面插入它的副本( A → A' → B → B' → … );② 设置副本的 random: A'.random = A.random.next ;③ 拆分出两条链表。
  • 为什么 A'.random = A.random.next 成立 :因为每个原节点的下一个节点恰好是它的副本,因此 A.random 的副本就是 A.random.next 。
  • 哈希表解法(更直观) :第一趟建 原节点 → 副本 的映射,第二趟设置 next 与 random 。空间 O(n)。
  • 拆分时的细节 :必须同时恢复原链表的 next 指针,否则会破坏输入。

常见陷阱

  • 只复制 next 而忘记 random :必须两趟处理(先建副本,再设 random),因为 random 可能指向尚未创建的节点。
  • 哈希表用 cur 作键但 Node 未实现 __hash__ :LeetCode 的 Node 默认按对象身份哈希,可用;若自定义了 __eq__ 需注意。
  • 交错法拆分时忘记恢复原链表 : cur.next = node.next 这一行是必须的,否则会破坏输入数据。
  • node.next = node.next.next if node.next else None 的边界 :最后一个副本的 next 为 None,必须处理。

参考实现

class Solution:
    def copyRandomList(self, head: 'Node') -> 'Node':
        if not head:
            return None

        # ① 交错插入副本:A -> A' -> B -> B' -> ...
        cur = head
        while cur:
            node = Node(cur.val)
            node.next = cur.next
            cur.next = node
            cur = node.next

        # ② 设置副本的 random
        cur = head
        while cur:
            if cur.random:
                cur.next.random = cur.random.next
            cur = cur.next.next

        # ③ 拆分两条链表
        new_head = head.next
        cur = head
        while cur:
            node = cur.next                 # 副本
            cur.next = node.next            # 恢复原链表
            node.next = node.next.next if node.next else None
            cur = cur.next
        return new_head

# 哈希表解法(空间 O(n),更直观):
# mapping = {}
# cur = head
# while cur:
#     mapping[cur] = Node(cur.val)
#     cur = cur.next
# cur = head
# while cur:
#     mapping[cur].next = mapping.get(cur.next)
#     mapping[cur].random = mapping.get(cur.random)
#     cur = cur.next
# return mapping.get(head)