复杂链表的复制
题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
假设原始链表为:下图中除去A'.B',C',D',E'的部分是原始链表,实线是正常指针,虚线是特殊指针指向特殊节点。经过第一个while循环后,变成下图
经过第二个while循环,变为:
使得A'指向C',D'指向B'
public RandomListNode Clone(RandomListNode head) {
if (Head == null)
return null;
RandomListNode cur = head;
//复制next 如原来是A->B->C 变成A->A'->B->B'->C->C'
while (cur != null) {
RandomListNode node = new RandomListNode(cur.label); //创建A
node.next = cur.next; //把B准备好,并赋给node.next
cur.next = node; //使得A->A'
cur = node.next; //把pCur移到B处
}
cur = head;
//复制random
while (cur != null) {
if (cur.random != null)
cur.next.random = cur.random.next;
cur = cur.next.next;
}
RandomListNode realHead = head.next; //head是A',B',C',D',E'链表的头
RandomListNode first = realHead;
RandomListNode last= head;
//拆分链表
while (first != null) {
last.next = last.next.next;
if (first.next != null)
first.next = first.next.next;
first = first.next;
last = last.next;
}
return realHead;
}
浙公网安备 33010602011771号