138.复制带随机指针的链表/剑指offer35.复杂链表的复制。简单易懂注释版0ms

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return head;
        }
        //将拷贝节点放到原节点后面,例如1->2->3这样的链表就变成了这样1->1'->2->2'->3->3'
        // 即复制原有结点并接在原有链表后面
        Node cur = head;
        while(cur != null){
            Node copy = new Node(cur.val);
            copy.next = cur.next;
            cur.next = copy;
            cur = cur.next.next;
        }

        // 复制随机结点
        Node cur2 = head;
        while(cur2 != null){
             if (cur2.random != null) cur2.next.random = cur2.random.next;
             cur2 = cur2.next.next;
        }
           
        //分离拷贝节点和原节点,变成1->2->3和1'->2'->3'两个链表,后者就是答案
        Node cur3 = head, dummy = head.next;
        while(cur3 != null && cur3.next != null){
            Node temp = cur3.next;
            cur3.next = temp.next;
            cur3 = temp;
        }
        return dummy;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值