1 題目描述
請實現 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]]
示例 2:
輸入:head = [[1,1],[2,1]]
輸出:[[1,1],[2,1]]
示例 3:
輸入:head = [[3,null],[3,0],[3,null]]
輸出:[[3,null],[3,0],[3,null]]
示例 4:
輸入:head = []
輸出:[]
解釋:給定的鏈表爲空(空指針),因此返回 null。
提示:
-10000 <= Node.val <= 10000
Node.random 爲空(null)或指向鏈表中的節點。
節點數目不超過 1000 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
2 解題思路
- 方法:原地修改
哈希的做法,在大多數公司的面試官面前並不是一個滿意的答案,所以需要知道原地修改的解法才能夠從容面對面試。
原地修改解法流程:
(1)複製一個新的節點在原有節點之後,如 1 -> 2 -> 3 -> null 複製完就是 1 -> 1 -> 2 -> 2 -> 3 - > 3 -> null
(2)從頭開始遍歷鏈表,通過 cur.next.random = cur.random.next 可以將複製節點的隨機指針串起來,當然需要判斷 cur.random 是否存在
(3)將複製完的鏈表一分爲二
3 解決代碼
- 方法:原地修改 Java代碼
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null){
return head;
}
//完成鏈表的複製
Node cur = head;
while(cur != null){
Node copyNode = new Node(cur.val);
copyNode.next = cur.next;
cur.next = copyNode;
cur = cur.next.next;
}
//完成鏈表複製節點的隨機指針複製
cur = head;
while(cur != null){
if(cur.random != null){
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
//將鏈表一分爲二
Node copyHead = head.next;
cur = head;
Node curCopy = head.next;
while(cur != null){
cur.next = cur.next.next;
cur = cur.next;
if(curCopy.next != null){
curCopy.next = curCopy.next.next;
curCopy = curCopy.next;
}
}
return copyHead;
}
}