輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的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)
{
if(pHead==null){
return null;
}
//在所有當前節點之後添加一個相同節點
RandomListNode pCur = pHead;
while (pCur!=null){
RandomListNode listNode = new RandomListNode(pCur.label);
listNode.next = pCur.next;
listNode.random = null;
pCur.next = listNode;
pCur = listNode.next;
}
//給random賦值
pCur=pHead;
while (pCur!=null){
if(pCur.random!=null)
pCur.next.random = pCur.random.next;
pCur=pCur.next.next;
}
//分離clone的鏈表,並還原原鏈表
pCur =pHead.next;
RandomListNode head = pHead.next;
RandomListNode cur = head;
pCur = pHead;
while (pCur!=null){
pCur.next = pCur.next.next;
if(cur.next!=null)
cur.next=cur.next.next;
cur=cur.next;
pCur = pCur.next;
}
return head;
}
}