剑指offer JZ25 复杂链表的复制

题目链接:

JZ25 复杂链表的复制

本题思路:
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        // base case
        if(pHead == null) return pHead;
        // 链表节点的复制
        // cur = cur.next.next跳到原链表下一个节点
        for(RandomListNode cur = pHead, copy = null; cur != null; cur = cur.next.next) {
            copy = new RandomListNode(cur.label); // 传入节点的值
            copy.next = cur.next; // 交接右侧指针
            cur.next = copy; // 交接左侧指针
        }
        // 拷贝链表的随机指针复制
        for(RandomListNode cur = pHead; cur != null; cur = cur.next.next) {
            if(cur.random != null) {
                cur.next.random = cur.random.next; // 在拷贝链表上操作 画图易理解
            }
        }
        // 分离出拷贝链表
        RandomListNode cur = pHead;
        RandomListNode copyHead = pHead.next;
        RandomListNode temp = null;
        // 逐个后移 当最后一个拷贝节点复制给cur
        // cur != null但cur.next == null 此时结束分离
        while(cur != null && cur.next != null) {
            temp = cur.next; // 拷贝链表从pHead.next向下传递
            cur.next = temp.next; // 原链表向下传递
            cur = temp; // 逐个后移
        }
        return copyHead;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值