題目描述
輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
}
}
思路:
實現:
/*
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
*/
public class Solution {
public RandomListNode Clone(RandomListNode pHead)
{
if (pHead == null)
return null;
//0 定義當前結點,爲後面判斷做準備
RandomListNode currentNode = pHead;
//1 先複製每個結點,複製的結點放在 被複制結點 的後面;
while (currentNode != null){
//1.1 創建一個新結點,新結點和舊鏈表的當前結點值一樣;
RandomListNode cloneNode = new RandomListNode(currentNode.label);
//1.2獲取舊鏈表當前結點的下一個結點
RandomListNode nextNode = currentNode.next;
//1.3 舊鏈表的當前結點 指向 新結點
currentNode.next = cloneNode;
//1.4 新結點 指向 舊鏈表的當前結點的下一個結點
cloneNode.next = nextNode;
//1.5 插入新結點完成後,舊鏈表的當前結點向後移動一個;
currentNode = nextNode;
}
//2 再遍歷一次鏈表,將舊結點的隨機指針複製給新結點;遍歷前先將當前結點重置頭結點;
//2.1 重置當前結點爲 頭結點
currentNode = pHead;
while (currentNode != null){
//2.1 當前結點的下一結點的隨機指針,等於當前結點的隨機指針所指向結點的下一個結點
currentNode.next.random = currentNode.random == null ? null : currentNode.random.next;
//2.2 當前結點跳到下一個舊結點;
currentNode = currentNode.next.next;
}
//3 將原鏈表和複製鏈表拆分開來
//3.1 重置當前結點爲 頭結點
currentNode = pHead;
//3.2 創建一個新的複雜鏈表的 頭結點 指向第一個 複製結點;
RandomListNode clonePHead = pHead.next;
while (currentNode != null){
RandomListNode cloneNode = currentNode.next;
currentNode.next = cloneNode.next;
cloneNode.next = cloneNode.next == null ? null : cloneNode.next.next;
currentNode = currentNode.next;
}
return clonePHead;
}
}