复杂链表的复制

img

//思路:

第一步,在每个节点的后面插入复制的节点

img

第二步,对复制节点的 random 链接进行赋值。

img

第三步,拆分。

img

public RandomListNode Clone(RandomListNode pHead) {
    if(pHead==null){
        return null;
    }

    //第一步,在每个节点的后面插入复制的节点
    RandomListNode cur=pHead;
    while (cur!=null){
        RandomListNode newNode = new RandomListNode(cur.label);
        newNode.next = cur.next;
        cur.next = newNode;
        cur=newNode.next;
    }

    //对复制节点的 random 链接进行赋值。
    cur=pHead;
    while(cur!=null){
        // cur 是当前的节点
        // cur.next 是复制的节点
        RandomListNode clone = cur.next;
        if(cur.random!=null){
            clone.random = cur.random.next; //
            //cur.random 是 cur 的random 指向的节点
            //cur.random.next 就是 cur.random.next 的复制节点
        }
        cur=clone.next;
    }

    //拆分
    cur=pHead;
    RandomListNode pCloneHead = pHead.next;
    while(cur.next!=null){ //拆分出 pHead 原来的链表,剩下的就是 pCloneHead 链表
        RandomListNode next = cur.next;
        cur.next = next.next;
        cur=next;
    }
    return pCloneHead;
}

https://www.mianshi.onlinehttps://www.i9code.cn

本文由博客一文多发平台 OpenWrite 发布!

逃跑的眼镜_bvbEK5
7 声望0 粉丝