35.复杂链表的复制

35. 复杂链表的复制

1 题目描述

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

示例

在这里插入图片描述

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

2 题目分析

​ 根据题目描述可知,该链表除过next指针域还有一个额外的random随机指向域,意味着除了复制每个结点的next信息还需要复制random信息,因此一个简单的方法是复制分成两步,第一步复制原始链表将next连接起来;第二步设置每个节点的random信息。但由于random位置不确定,因此要定位一个节点N的random节点就需要从原始链表的头部开始找,时间复杂度为O(n²)。

​ 一个优化方法是牺牲时间换空间,用一个hashmap去保存复制后的节点N’,这样就能用O(1)的时间复杂度根据S找到S’。

​ 本题用一种不使用辅助空间的方法来实现O(n)的时间复杂度,具体是我们遍历链表的过程中将每一个节点复制到当前节点的右侧,然后将偶数的结点分离出来返回即可。

3 代码

// 复杂链表的复制
public Node copyRandomList(Node head) {
    if (head == null) return null;

    // 1. 复制原链表以及next信息在每个节点的右侧
    cloneNode(head);
    // 2. 复制random信息
    connectRandom(head);
    // 3. 分离返回偶数的链表头结点
    return reConnectNode(head);
}

private Node reConnectNode(Node head) {
    Node node = head;
    Node clonedHead = node.next;
    Node cloneNode = clonedHead;
    while (node != null) {
        node.next = node.next.next;
        if (cloneNode != null && cloneNode.next != null) {
            cloneNode.next = cloneNode.next.next;
        }
        node = node.next;
        cloneNode = cloneNode != null ? cloneNode.next : null;

    }
    return clonedHead;
}

/*
        连接random信息
     */
private void connectRandom(Node head) {
    Node node = head;
    while (node != null) {
        Node cloned = node.next;
        if (node.random != null) {
            cloned.random = node.random.next;
        }
        node = cloned.next;
    }
}

/*
        克隆每一个节点在原链表的右侧
     */
private void cloneNode(Node head) {
    Node node = head;
    while (node != null) {
        // 复制node
        Node cloned = new Node(node.val);
        cloned.next = node.next;
        node.next = cloned;
        node = cloned.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值