这道题一定要注意括号里面的东西,(输出结果中请不要返回参数中的节点引用)。也就是说,
最后的返回的链表中的节点一定不能和原来链表中的某个节点指向同一个节点,即不能引用。
所以必须分三步进行处理:
1、复制每个节点,如:复制节点A得到A1,将A1插入节点A后面
2、遍历链表,A1->random = A->random->next; 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(null == pHead){
return null;
}
RandomListNode cur = pHead;
while(cur!=null){
RandomListNode temp = new RandomListNode(cur.label);
temp.next = cur.next;
cur.next = temp;
cur = temp.next;
}
cur = pHead;
while(cur!=null){
if(cur.random != null){
cur.next.random = cur.random.next;
}
cur=cur.next.next;
}
RandomListNode result = pHead.next;
RandomListNode pCur = result;
cur = pHead;
while(cur!= null){
cur.next = cur.next.next;
if(pCur.next != null){
pCur.next= pCur.next.next;
}
cur=cur.next;
pCur = pCur.next;
}
return result;
}
}
本文介绍了一种特殊的链表复制算法,该算法能够处理带有随机指针的复杂链表结构。通过三个步骤实现:首先复制节点并插入原节点之后;接着更新新节点的随机指针;最后分离原始链表和复制链表。
274

被折叠的 条评论
为什么被折叠?



