35. 复杂链表的复制
1 题目描述
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
示例
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
2 题目分析
根据题目描述可知,该链表除过next指针域还有一个额外的random随机指向域,意味着除了复制每个结点的next信息还需要复制random信息,因此一个简单的方法是复制分成两步,第一步复制原始链表将next连接起来;第二步设置每个节点的random信息。但由于random位置不确定,因此要定位一个节点N的random节点就需要从原始链表的头部开始找,时间复杂度为O(n²)。
一个优化方法是牺牲时间换空间,用一个hashmap去保存复制后的节点N’,这样就能用O(1)的时间复杂度根据S找到S’。
本题用一种不使用辅助空间的方法来实现O(n)的时间复杂度,具体是我们遍历链表的过程中将每一个节点复制到当前节点的右侧,然后将偶数的结点分离出来返回即可。
3 代码
// 复杂链表的复制
public Node copyRandomList(Node head) {
if (head == null) return null;
// 1. 复制原链表以及next信息在每个节点的右侧
cloneNode(head);
// 2. 复制random信息
connectRandom(head);
// 3. 分离返回偶数的链表头结点
return reConnectNode(head);
}
private Node reConnectNode(Node head) {
Node node = head;
Node clonedHead = node.next;
Node cloneNode = clonedHead;
while (node != null) {
node.next = node.next.next;
if (cloneNode != null && cloneNode.next != null) {
cloneNode.next = cloneNode.next.next;
}
node = node.next;
cloneNode = cloneNode != null ? cloneNode.next : null;
}
return clonedHead;
}
/*
连接random信息
*/
private void connectRandom(Node head) {
Node node = head;
while (node != null) {
Node cloned = node.next;
if (node.random != null) {
cloned.random = node.random.next;
}
node = cloned.next;
}
}
/*
克隆每一个节点在原链表的右侧
*/
private void cloneNode(Node head) {
Node node = head;
while (node != null) {
// 复制node
Node cloned = new Node(node.val);
cloned.next = node.next;
node.next = cloned;
node = cloned.next;
}
}