題目描述
輸入一個複雜連結清單(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),傳回結果為複制後複雜連結清單的head。(注意,輸出結果中請不要傳回參數中的節點引用,否則判題程式會直接傳回空)
解題思路

image
參考代碼
/*
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;
//複制節點 A->B->C 變成 A->A'->B->B'->C->C'
RandomListNode head = pHead;
while(head != null){
RandomListNode node = new RandomListNode(head.label);
node.next = head.next;
head.next = node;
head = node.next;
}
//複制random
head = pHead;
while(head != null){
head.next.random = head.random == null ? null : head.random.next;
head = head.next.next;
}
//折分
head = pHead;
RandomListNode chead = head.next;
while(head != null){
RandomListNode node = head.next;
head.next = node.next;
node.next = node.next == null ? null : node.next.next;
head = head.next;
}
return chead;
}
}