链表-复制含有随机指针节点的链表

//复制含有随机指针节点的链表
public Node copyLinkedListWithRand(Node head){
    if(head==null){
        return null;
    }
    Node cur=head;
    Node next=null;
    //复制并链接每一个节点
    while(cur!=null){
        next=cur.next;
        cur.next=new Node(cur.value);
        cur.next.next=next;
        cur=next;
    }
    cur=head;
    Node curCopy=null;
    //设置复制节点的rand指针
    while(cur!=null){
        next=cur.next.next;
        curCopy=cur.next;
        curCopy.rand=cur.rand!=null?cur.rand.next:null;
        cur=next;
    }
    Node res=head.next;
    cur=head;
    //拆分
    while(cur!=null){
        next=cur.next.next;
        curCopy=cur.next;
        cur.next=next;
        curCopy.next=next!=null?next.next:null;
        cur=next;
    }   
    return res;
}

猜你喜欢

转载自blog.csdn.net/weixin_42146769/article/details/88393155