含随机指针链表的深拷贝

思路:
1.将每一个节点复制后插入到原节点的后面,新的random域先初始化为null
2.新节点的random为旧节点random指向的下一个节点
3.拆分:将这个链表的新旧节点拆分开,返回新节点

class A{
    int data;
    A next;
    A random;
    public A(int data,A next,A random){
        this.data=data;
        this.next=next;
        this.random=random;
    }
}
public class RandomCopy {
    A head;
    public A copyRandomList(){
        if(this.head==null){
            return null;
        }
        A cur=this.head;
        while(cur!=null){
            A node=new A(cur.data,cur.next,null);
            A tmp=cur.next;
            cur.next=node;
            cur=tmp;
        }
        cur=this.head;
        while(cur!=null){
            if(cur.random!=null){
                cur.next.random=cur.random.next;
            }else{
                cur.next.random=null;
            }
            cur=cur.next.next;
        }
        //拆
        cur=this.head;
        A newHead=cur.next;
        while(cur.next!=null){
            A tmp=cur.next;
            cur.next=tmp.next;
            cur=tmp;
        }
        return newHead;
    }
}

发布了67 篇原创文章 · 获赞 12 · 访问量 1512

猜你喜欢

转载自blog.csdn.net/qq_42174669/article/details/102959785