输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的 head。
比一般的链表添加了一个随机指针
public class RandomListNode {
int label;
RandomListNode next = null;
RandomListNode random = null;
RandomListNode(int label) {
this.label = label;
}
}
第一步,在每个节点的后面插入复制的节点。
第二步,对复制节点的 random 链接进行赋值。
第三步,拆分。
/*
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;
while(cur!=null){
//克隆节点的值是cur.label
RandomListNode clone=new RandomListNode(cur.label);
clone.next=cur.next;
cur.next=clone;
cur=clone.next;
}
//建立random链接
cur=pHead;
while(cur!=null){
RandomListNode clone=cur.next;
if(cur.random!=null)
{
clone.random=cur.random.next;
}
cur=clone.next;
}
//拆分成两个链表
cur=pHead;
RandomListNode pCloneHead=pHead.next;
while(cur.next!=null){
RandomListNode next=cur.next;
cur.next=next.next;
cur=next;
}
return pCloneHead;
}
}
错误:
1、第一步插入新节点和第二步建立random链接时,while内的判断条件是while (cur != null)
第三步才是while (cur.next != null)
2、新建节点时,RandomListNode clone = new RandomListNode(cur.label);
cur.label是代表新节点的值
3、插入节点时,先保存节点的next,然后连接新的节点,clone.next = cur.next;
cur.next = clone;
cur = clone.next;
4、建立random连接时,要判断该节点是否有random连接