力扣138【随机链表的复制】

给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。

构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和random
指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。

例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有x.random --> y 。
返回复制链表的头节点。

这题比较难的是理解题意:中文翻译过来比较难理解,实际上就是深拷贝一个链表,(这个链表多一个random属性,它指向链表某个节点),深拷贝的这个链表也必须有这种结构关系!

解决方法:关键就是解决深拷贝代码的random指针,根据原链表的位置去找新链表的相对位置,这里要么用map记录索引位置去找;要么就用更好的思路,将新链表的每一个节点先穿在原链表后面!

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        //这里将节点的拷贝节点直接插入其后真是神来之笔
        for (Node node = head; node != null; node = node.next.next) {
            Node nodeNew = new Node(node.val);
            nodeNew.next = node.next;
            node.next = nodeNew;
        }
        //只需要找原链表的random节点,后面跟的一定是此节点的random节点
        for (Node node = head; node != null; node = node.next.next) {
            Node nodeNew = node.next;
            //注意可能有null
            nodeNew.random = (node.random != null) ? node.random.next : null;
        }

		//最后就是遍历摘下来新链表
        Node headNew = head.next;
        for (Node node = head; node != null; node = node.next) {
            Node nodeNew = node.next;
            node.next = node.next.next;
            nodeNew.next = (nodeNew.next != null) ? nodeNew.next.next : null;
        }

        return headNew;
    }
}


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

miss writer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值