题面
给你一个长度为 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或指向链表中的节点。
分析
-
可以遍历两次原链表,并存储原链表中节点到 index 的映射
-
这样再次遍历原链表时,可以直接使用 index 来读取新链表中节点的指针
-
代码实现
/* // Definition for a Node. class Node { public: int val; Node* next; Node* random; Node(int _val) { val = _val; next = NULL; random = NULL; } }; */ class Solution { public: Node* copyRandomList(Node* head) { if (head == nullptr) return nullptr; Node *newHead = nullptr, *pre = nullptr; vector<Node*> nodes; std::unordered_map<Node*, int> nodeIndex; Node* cur = head; while (cur != nullptr) { Node* temp = new Node(cur->val); nodeIndex[cur] = nodes.size(); nodes.push_back(temp); if (pre != nullptr) pre->next = temp; else { newHead = temp; } pre = temp; cur = cur->next; } cur = head; pre = newHead; while (cur != nullptr) { if (cur->random != nullptr) pre->random = nodes[nodeIndex[cur->random]]; cur = cur->next; pre = pre->next; } return newHead; } }; -
那么可以不使用哈希表吗?
-
可以直接将新节点插入到源节点的后面,这样,当旧节点 1 的 random 指向 3 时,可以直接访问 3 的后继节点 3’ 获取新节点
-
代码实现
class Solution { public: Node* copyRandomList(Node* head) { for (Node* cur = head; cur; cur = cur->next->next) { cur->next = new Node(cur->val, cur->next, nullptr); } for (Node* cur = head; cur; cur = cur->next->next) { if (cur->random) { cur->next->random = cur->random->next; } } Node dummy(0); Node* tail = &dummy; for (Node* cur = head; cur; cur = cur->next, tail = tail->next) { Node* copy = cur->next; // 新节点 tail->next = copy; // 把新节点插在 tail 的后面,构建新的链表 cur->next = copy->next; // 恢复原节点的 next } return dummy.next; } };