题链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
分三步:
(1)复制每一个节点,使得复制后的节点都在当前节点的下一个节点
(2)原生链表的节点的指向任意节点,使复制的节点也都指向某一任意节点
(3)重新连接节点,把原生节点重新连接起来,把克隆后的节点连接起来
写链表的题,尽量把链表结构和迭代过程画出来,可以清晰的看出迭代过程,也更容易找出错误。
var copyRandomList = function(head) {
if (head == null) {
return null;
}
//克隆节点
let tempHead = head;
while (tempHead != null) {
let cloneNode = new Node(tempHead.val);
let temp = tempHead.next;
tempHead.next = cloneNode;
cloneNode.next = temp;
tempHead = cloneNode.next;
}
//克隆Random指针
tempHead = head;
while (tempHead != null) {
let cloneNode = tempHead.next;
if (tempHead.random != null) {
let temp = tempHead.random;
cloneNode.random = temp.next;
}
tempHead = cloneNode.next;
}
//将克隆节点连接起来
let tempNode = head.next;
let resNode = tempNode;
head.next = tempNode.next;
head = head.next;
while (head != null) {
tempNode.next = head.next;
head.next = head.next.next;
tempNode = tempNode.next;
head = head.next;
}
return resNode;
};
假设链表长度为n:
时间复杂度:O(n)
空间复杂度:O(1)