复杂链表的复制

题目描述

输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
 
这个题有两种解法,第一种是用hashmap把原表random(随机指针)对应存起来,再复原,可是这个空间复杂度太高
第二种方法,把原链表的a-b-c-d变成 a-a1-b-b1-c-c1-d-d1这样,a1的random指针应该指向a指针指向的位置的下一个位置(很好理解)
 
注意:一定要先将a-b-c-d变成 a-a1-b-b1-c-c1-d-d1,再进行随机指针的变更,(把所有的next指针调好了,再调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)
    {
        RandomListNode Head=pHead;
        if(pHead==null){
            return null;
        }
        RandomListNode cur=pHead;
        RandomListNode next=pHead;
        while(cur!=null){
            next=cur.next;
            cur.next=new RandomListNode(cur.label);
            cur.next.next=next;
            cur=next;
        }
        
        cur=pHead;
        next=pHead;
        while(cur!=null){
            cur.next.random=cur.random==null?null:cur.random.next;
            cur=cur.next.next;;
        }
        RandomListNode pHead1=Head.next;
        while(Head!=null){
            next=Head.next.next;
            Head.next.next=next==null?null:next.next;
            Head.next=next;
            Head=next;
        }
        return pHead1;

    }
}
原文地址:https://www.cnblogs.com/tobemaster/p/5903669.html