138 复制带随机指针的链表

本文最后更新于:2022年4月9日 中午

给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。

构造这个链表的 深拷贝**。 深拷贝应该正好由 n 个 **全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点

例如,如果原链表中有 XY 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 xy ,同样有 x.random --> y

返回复制链表的头节点。

用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

  • val:一个表示 Node.val 的整数。
  • random_index:随机指针指向的节点索引(范围从 0n-1);如果不指向任何节点,则为 null

你的代码 接受原链表的头节点 head 作为传入参数。

示例 1:

img

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

示例 2:

img

1
2
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]

示例 3:

img

1
2
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]

示例 4:

1
2
3
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。

提示:

  • 0 <= n <= 1000
  • -10000 <= Node.val <= 10000
  • Node.random 为空(null)或指向链表中的节点。

Solution

题目同剑指offer – 复杂链表的复制

  • 利用 map 保留过曾经访问过的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// @lc code=start
/*
// 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;
unordered_map<Node*, Node*> nodeMap;
for (auto *cur = head; cur != nullptr; cur = cur->next) {
nodeMap[cur] = new Node(cur->val);
}
for (auto *cur = head; cur != nullptr; cur = cur->next) {
nodeMap[cur]->next = nodeMap[cur->next];
nodeMap[cur]->random = nodeMap[cur->random];
}
return nodeMap[head];
}
};
// @lc code=end
  • 将链表的每个节点在其后复制一份

    1、遍历链表,复制每个结点,如复制结点A得到A1,将结点A1插到结点A后面;
    2、重新遍历链表,复制老结点的随机指针给新结点,如A1.random = A.random.next;
    3、拆分链表,将链表拆分为原链表和复制后的链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == nullptr) return nullptr;
Node *cur = head;
while (cur) {
Node *node = new Node(cur->val);
node->next = cur->next;
cur->next= node;
cur = node->next;
}

Node *cur1 = head, *cur2;
while (cur1) {
cur2 = cur1->next;
if (cur1->random)
cur2->random = cur1->random->next;
cur1 = cur2->next;
}

// 分离链表
cur1 = head, cur2;
Node *phead = head->next;
while (cur1) {
cur2 = cur1->next;
cur1->next = cur2->next;
cur1 = cur1->next;
if (cur1)
cur2->next = cur1->next;
}
return phead;
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!