LeetCode 题解工作台
随机链表的复制
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。 构造这个链表的 深拷贝 。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 链表指针操作
答案摘要
我们可以定义一个虚拟头节点 ,用一个指针 指向虚拟头节点,然后遍历链表,将链表中的每个节点都复制一份,并将每个节点及其复制节点的对应关系存储在哈希表 中,同时连接好复制节点的 指针。 接下来再遍历链表,根据哈希表中存储的对应关系,将复制节点的 指针连接好。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路
题目描述
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
val:一个表示Node.val的整数。random_index:随机指针指向的节点索引(范围从0到n-1);如果不指向任何节点,则为null。
你的代码 只 接受原链表的头节点 head 作为传入参数。
示例 1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]] 输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
示例 2:

输入:head = [[1,1],[2,1]] 输出:[[1,1],[2,1]]
示例 3:

输入:head = [[3,null],[3,0],[3,null]] 输出:[[3,null],[3,0],[3,null]]
提示:
0 <= n <= 1000-104 <= Node.val <= 104Node.random为null或指向链表中的节点。
解题思路
方法一:哈希表 + 模拟
我们可以定义一个虚拟头节点 ,用一个指针 指向虚拟头节点,然后遍历链表,将链表中的每个节点都复制一份,并将每个节点及其复制节点的对应关系存储在哈希表 中,同时连接好复制节点的 指针。
接下来再遍历链表,根据哈希表中存储的对应关系,将复制节点的 指针连接好。
时间复杂度 ,空间复杂度 。其中 为链表的长度。
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: "Optional[Node]") -> "Optional[Node]":
d = {}
dummy = tail = Node(0)
cur = head
while cur:
node = Node(cur.val)
tail.next = node
tail = tail.next
d[cur] = node
cur = cur.next
cur = head
while cur:
d[cur].random = d[cur.random] if cur.random else None
cur = cur.next
return dummy.next
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate understands how to handle linked list pointers effectively.
- question_mark
The candidate uses efficient space management in their solution.
- question_mark
The solution works for lists with random pointers pointing to multiple nodes.
常见陷阱
外企场景- error
Failing to correctly manage the random pointers, especially in cases where they point to null.
- error
Not properly separating the original and copied lists, leading to shared nodes.
- error
Overcomplicating the solution with unnecessary space usage, like excessive use of additional data structures.
进阶变体
外企场景- arrow_right_alt
Handle the case where the input list is empty.
- arrow_right_alt
Extend the problem by allowing more complex random pointer relationships, such as multiple nodes referencing the same random node.
- arrow_right_alt
Modify the problem to work with doubly linked lists, where each node has both next and previous pointers in addition to random pointers.