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

在这里插入图片描述剑指 Offer 35. 复杂链表的复制

我的思路

首先分析该题,该链表相对于普通链表多了随机指针,所以正常的遍历就无法完全复制,必须要通过一种方法来保存老节点的信息(random指向谁),为了实现信息保存,我们可以使用哈希表来建立老节点对应新节点的映射,这样新节点的随机指针指向的就是老节点的随机指针映射的新指针.
核心代码如下



class Solution {
    public Node copyRandomList(Node head) {
        if(head == null) return null;
        Node cur = head;
        Map<Node, Node> map = new HashMap<>();
        // 3. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
        while(cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        // 4. 构建新链表的 next 和 random 指向
        while(cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        // 5. 返回新链表的头节点
        return map.get(head);
    }
}

思路二

为了保存节点信息,我们也可以不用哈希表,转而使用在老节点后插入新节点来实现信息的调取,这样新节点的随机指针就是老节点随机指针的下一个(逻辑上也创建了null的下一个指针,但是在赋值时要注意),方法如下

public Node copyRandomList(Node head) {
        if(head==null)
            return null;
        Node cur=head;
        while(cur!=null){//插入新链表
            Node temp = new Node(cur.val);
            Node temp1= cur.next;
            cur.next=temp;
            temp.next=temp1;
            cur=temp1;
        }
        cur=head;
        while (cur!=null){//补上随机指针
            if(cur.random!=null)
                cur.next.random=cur.random.next;
            else
                cur.next.random=null;
            cur=cur.next.next;
        }
       cur=head.next;
        Node tt = head;
        Node t1 = new Node(6);
        Node t2 = new Node(1);
        Node t3= head;
        int i=0;
        while (t3!=null){//新旧分离,这里写的不是很好可以去看原题题解
            if(i==0){
                t1.next=t3;
                t1= t1.next;
                i=1;
            }else{
                t2.next=t3;
                t2=t2.next;
                i=0;
            }
            t3=t3.next;
        }
        t1.next=null;
        return cur;
    }

疑问与困难

题解中说第二种思路空间复杂度为o1,但是不也是创建了n个节点吗?

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值