复杂链表的复制

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


示例 4:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

感谢Krahets大神的详细解释,传送门https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/solution/jian-zhi-offer-35-fu-za-lian-biao-de-fu-zhi-ha-xi-/

class Solution {
        public Node copyRandomList(Node head) {
//            return copyRandomListI(head);
            //方法二:
            //1.复制各节点,构建拼接链表
            //假设原链表为node1->node2->...,拼接链表为node1->node1new->node2->node2new->...
            //2.建立新链表各节点的random指向
            //假设原链表的cur节点的random指向为cur.random,那么新节点cur.next的random指向为cur.random.next
            //3.将链表进行拆分
            //定义两指针prev和cur分别指向原链表和新链表的头节点,遍历拼接链表执行
            //prev.next=prev.next.next,cur.next=cur.next.next将链表进行拆分
            //4.返回新链表的头节点
            if (head == null) return null;
            Node cur = head;
            //复制各节点,构建拼接链表
            while (cur != null) {
                Node temp = new Node(cur.val);
                temp.next = cur.next;
                cur.next = temp;
                cur = temp.next;
            }
            cur = head;
            //建立新链表的random指向
            while (cur != null) {
                if (cur.random != null) {
                    cur.next.random = cur.random.next;
                }
                cur = cur.next.next;
            }
            //将拼接链表进行拆分
            cur = head.next;
            Node prev = head, res = head.next;
            while (cur.next != null) {
                prev.next = prev.next.next;
                cur.next = cur.next.next;
                prev = prev.next;
                cur = cur.next;
            }
            //处理原链表尾节点
            prev.next = null;
            return res;
        }

       //方法一:使用hashMap缓存,时间复杂度O(n),空间复杂度O(n)
       //1.遍历链表,复制各节点,并缓存原节点->新节点的映射关系
       //2.利用缓存的原节点,新节点直接复制原节点的的next和random指针关系
       //3.利返回新链表的头节点
       private Node copyRandomListI(Node head) {
           if (head == null) return null;
           Map<Node, Node> map = new HashMap<>();
           Node cur = head;
           //先复制各节点,建立Map映射关系
           while (cur != null) {
               map.put(cur, new Node(cur.val));
               cur = cur.next;
           }
           cur = head;
           //建立新链表的next和random指针关
           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);
       }
   }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值