题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点);
返回结果为复制后的复杂链表的head;
注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空;
解题思路
1.复制每个节点,原来是A->B->C,现在是A->A'->B->B'->C->C';
2.复制random,即A'.random = A.random->next;
3.将链表拆分成原链表和复制后的链表;
public RandomListNode Clone(RandomListNode pHead) {
if (pHead == null){
return null;
}
RandomListNode pCur = pHead;
//复制next,原来是A->B->C,现在是A->A'->B->B'->C->C'
while(pCur != null){
RandomListNode newNode = new RandomListNode(pCur.label);
newNode.next = pCur.next;
pCur.next = newNode;
pCur = newNode.next;
}
pCur = pHead;
//复制random,pCur是原来链表的结点 pCur.next是复制pCur的结点
while (pCur != null){
if (pCur.random != null){
pCur.next.random = pCur.random.next;
}
pCur = pCur.next.next;
}
RandomListNode result = pHead.next; //保存结果链表
RandomListNode curent = pHead.next;
pCur = pHead; //保存原来的链表
//现在是这种关系:pCur -> current
//拆分列表
while (pCur != null){
pCur .next = pCur .next.next;
if (curent.next != null){ //注意这个地方,当current是最后的那个节点时,current.next为null
//当current.next == null时,是不能使用curent.next.next的
curent.next = curent.next.next;
}
curent = curent.next;
pCur = pCur.next;
}
return result;
}