剑指 Offer 35. 复杂链表的复制

题目描述:

      请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。

示例1:

输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]

示例2:
在这里插入图片描述
输入:head = [[1,1],[2,1]]
输出:[[1,1],[2,1]]

示例3:
在这里插入图片描述
输入:head = [[3,null],[3,0],[3,null]]
输出:[[3,null],[3,0],[3,null]]

示例4:
输入:head = []
输出:[]
解释:给定的链表为空(空指针),因此返回 null。

解题思路:

1、利用hashMap:
     这里的难点是如何找到结点的随机random 指针,如何按照常规的查找方法从head节点开始查找,那么每一个节点时候都要遍历一遍链表,这样时间复杂度为O(n^2)。可以使用一个hashMap将所有节点存储起来,这样就可以保存其random指针信息(因为random指针说白了也就是链表中一个普通的节点),最后就可以通过hashMap取出其random节点。这样的时间复杂度为O(n)

2、三步走:
     上述解法的时间复杂度为O(n),但是借助了一个hashMap,下面介绍一种没有借助hashMap且时间复杂度为O(n)的解法,简单来说,分为三步:(1)复制每一个节点,使得复制后的节点都在当前节点的下一个节点;(2)原生链表的节点的指向任意节点,使复制的节点也都指向某一任意节点;(3)重新连接节点,把原生节点重新连接起来,把克隆后的节点连接起来(即将链表拆分为原链表和复制链表),最后返回复制链表。
以上过程可以用下图表示:
在这里插入图片描述注: 以上解法参考于LeetCode中Markus大佬的题解

实现代码:

	//解法1:使用hashMap
    public Node copyRandomList(Node head) {
        HashMap<Node,Node> map = new HashMap<>();
        Node cur = head;
        while(cur != null){
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        while(cur != null){
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }

    //解法2
    public Node copyRandomList1(Node head) {
        if(head == null)
            return head;
        Node cur = head;
        //第一步:拷贝链表
        while(cur != null){
            Node next = cur.next;
            Node clone = new Node(cur.val);
            cur.next = clone;
            clone.next = next;
            cur = clone.next;
        }

        cur = head;
        //第二步:连接复制节点的随机节点
        while(cur != null){
            Node clone = cur.next;
            clone.random = cur.random != null ? cur.random.next : null;
            cur = clone.next;
        }

        cur = head;
        //第三步:拆分成原链表和复制链表
        Node res = head.next;
        while(cur != null){
            Node clone = cur.next;
            cur.next = clone.next;
            clone.next = cur.next != null ? cur.next.next : null;
            cur = cur.next;
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值