题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
题解
思路:
-
把复制的结点链接在原始链表的每一对应结点后面
-
把复制的结点的random指针指向被复制结点的random指针的下一个结点
- 拆分成两个链表,奇数位置为原链表,偶数位置为复制链表,注意复制链表的最后一个结点的next指针不能跟原链表指向同一个空结点None,next指针要重新赋值None(判定程序会认定你没有完成复制)
/*
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 head = pHead;
//复制每个节点
while(head != null){
RandomListNode curr = new RandomListNode(head.label);
//保留当前节点的下一个节点
RandomListNode next = head.next;
//将复制节点插入当前节点后
head.next = curr;
curr.next = next;
head = next;
}
//复制每个节点的随机引用
head = pHead;
while(head != null){
head.next.random = head.random == null ? null : head.random.next;
head = head.next.next;
}
//拆分链表
head = pHead;
RandomListNode clone = pHead.next;
while(head != null){
RandomListNode cloneNode = head.next;
//将原链表复位
head.next = cloneNode.next;
cloneNode.next = cloneNode.next == null ? null : cloneNode.next.next;
head = head.next;
}
return clone;
}
}