複雜鏈表的複製
請實現 copyRandomList 函數,複製一個複雜鏈表。在複雜鏈表中,每個節點除了有一個 next 指針指向下一個節點,還有一個 random 指針指向鏈表中的任意節點或者 null。
示例1:
輸入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
輸出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
步驟:
- 將新節點
A',B',C'...
插入到原鏈表A,B,C...
中
- 找到各節點random值,根據相對位置給新鏈表創建random值
- 分成兩個鏈表
/**
* @param {Node} head
* @return {Node}
*/
var copyRandomList = function (head) {
if (!head) return null;
let now = head;
while (now) {
let cloneNode = new Node(now.val);
/* 新結點插入到中間 */
cloneNode.next = now.next;
now.next = cloneNode;
/* 遍歷下一個 */
now = cloneNode.next;
}
/* 賦random值 */
now = head;
while (now) {
if (now.random)//根據相對位置找到對應節點
now.next.random = now.random.next;
now = now.next.next;
}
/* 拆分爲兩個新鏈表 */
let root = head.next, tmp;
now = head;
while (now.next) {
tmp = now.next;
now.next = now.next.next;
now = tmp;
}
return root;
};