题目描述
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
1)对链表的每一个节点进行复制
1 -> 2 -> 3 -> 4 复制完变成1 -> 1` ->2 -> 2` -> 3 -> 3` -> 4 -> 4`
2)将rand的值设置给复制的节点
如果1.rand -> 3 那么就应该赋值 1`.rand - > 3`
3)最后将两个链表拆分
/*
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 cur = pHead;
RandomListNode next = null;
while(cur != null){
next = cur.next;
cur.next = new RandomListNode(cur.label);
cur.next.next = next;
cur = next;
}
cur = pHead;
RandomListNode copynode = null;
while(cur != null){
next = cur.next.next;
cur.next.random = cur.random != null ? cur.random.next : null;
cur = next;
}
RandomListNode res = pHead.next;
cur = pHead;
while (cur != null){
next = cur.next.next;
copynode = cur.next;
cur.next = next;
copynode.next = next != null ? next.next : null;
cur = next;
}
return res;
}
}