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

请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
在这里插入图片描述
作者:jyd
链接: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-/
来源:力扣(LeetCode)

思路:对于普通的链表复制,即没有random节点,可以通过每一轮创建新节点,并维护当前节点cur和前驱节点pre,来进行复制。

class Solution {
    public Node copyRandomList(Node head) {
        //普通单链表
        Node cur = head;
        Node dum = new Node(0);
        Node pre = dum;
        //cur!=null,说明不为空需要复制
        while(cur!=null){
            Node node = new Node(cur.val);
            pre.next = node;
            cur = cur.next;
            pre = pre.next;
        }
        return dum.next;
    }
}

对于本题,有random节点,因此不能再像普通节点一样了。
第一种方法,构建HashMap。让新老节点进行一一对应,思路简单,但空间复杂度为O(n)

class Solution {
    public Node copyRandomList(Node head) {
        //用HashMap
        if(head==null) return null;
        //初始化
        Node cur = head;
        Map<Node, Node> map = new HashMap<Node,Node>();
        //将新老链表对应起来
        while(cur!=null){
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        //建立联系
        cur = head;
        while(cur!=null){
            Node temp = map.get(cur);
            temp.next = map.get(cur.next);
            temp.random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}

第二种思路,首先迭代创建新节点,对老链表进行拼接,老——新——老——新…,之后为新节点添加random节点,最后进行拆分,将老链表和新链表拆开,返回新链表
在这里插入图片描述

        //拼接与拆分
        if(head==null) return null;
        //拼接
        Node oldNode = head;
        Node newNode = null;
        while(oldNode!=null){
            newNode = new Node(oldNode.val);
            newNode.next = oldNode.next;
            oldNode.next = newNode;
            oldNode = newNode.next;
        }
        //添加random
        oldNode = head;
        while(oldNode!=null){
            if(oldNode.random!=null){
                oldNode.next.random = oldNode.random.next;
            }        
            oldNode = oldNode.next.next;
        }
        //拆分
        Node newHead = head.next;
        oldNode = head;
        newNode = head.next;
        while(newNode.next!=null){
            oldNode.next = oldNode.next.next;
            newNode.next = newNode.next.next;
            oldNode = oldNode.next;
            newNode = newNode.next;
        }
        oldNode.next = null;
        return newHead;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值