138. 随机链表的复制
构造这个链表的 深拷贝。
Categories:
#### 题意:
给你一个长度为 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
作为传入参数。
难度:
中等
分析:
和通常的深拷贝不同的是, 这里的节点多了随机指针
那么在拷贝随机指针之前, 就必须有原链表
因此分为三步
- 拷贝原链表
- 拷贝随机指针
- 分离链表
复制节点并插入原节点后面:
while (cur != null) {
Node newNode = new Node(cur.val);
newNode.next = cur.next;
cur.next = newNode;
cur = newNode.next;
}
比如原链表:A->B->C 变成 A->A’->B->B’->C->C'
复制随机指针:
while (cur != null) {
if (cur.random != null) {
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
利用第一步创建的节点关系,设置复制节点的random指针:
- 如果原节点A的random指向节点C
- 那么A’的random就应该指向C’(即C的next)
分离两个链表:
while (cur != null) {
Node next = cur.next.next;
Node copy = cur.next;
copyCur.next = copy;
copyCur = copy;
cur.next = next;
cur = next;
}
将交织在一起的链表分开:
- 原链表恢复原样:A->B->C
- 得到复制的链表:A’->B’->C'
整体:
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return null;
}
// 第一步:在每个原节点后创建一个新节点
Node cur = head;
while (cur != null) {
Node newNode = new Node(cur.val);
newNode.next = cur.next;
cur.next = newNode;
cur = newNode.next;
}
// 第二步:处理random指针
cur = head;
while (cur != null) {
if (cur.random != null) {
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
// 第三步:分离两个链表
Node dummy = new Node(0);
Node copyCur = dummy;
cur = head;
while (cur != null) {
// 保存下一个原始节点
Node next = cur.next.next;
// 复制的节点
Node copy = cur.next;
copyCur.next = copy;
copyCur = copy;
// 恢复原始链表
cur.next = next;
cur = next;
}
return dummy.next;
}
}