题目描述:
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
思路:
- 复制并插入:复制旧链表的每个结点,如:复制A得到A1,将A1插入A的后面;
- 遍历链表,补充新结点的 random 域,如:A1.random = A.random.next;
- 拆分:将链表分成原链表和复制后的链表。
具体代码如下:
/*
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 oldCur = pHead;
//1.复制并插入
while(oldCur != null){
RandomListNode newNode = new RandomListNode(oldCur.label);
newNode.next = oldCur.next;
oldCur.next = newNode;
oldCur = newNode.next;
}
oldCur = pHead;
//2.修改新链表的random域
while(oldCur != null){
RandomListNode newCur = oldCur.next;
if(oldCur.random != null) {
newCur.random = oldCur.random.next;
}
oldCur = newCur.next;
}
//3.拆分
oldCur = pHead;
RandomListNode res = pHead.next;
RandomListNode tmp = oldCur.next;
while(oldCur.next != null){
oldCur.next = tmp.next;
oldCur = tmp;
tmp = tmp.next;
}
return res;
}
}