Leetcode:138. 复制带随机指针的链表

Leetcode:138. 复制带随机指针的链表

题目描述

给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。

要求返回这个链表的 深拷贝。 

我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:

val:一个表示 Node.val 的整数。
random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  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。

提示:

-10000 <= Node.val <= 10000
Node.random 为空(null)或指向链表中的节点。
节点数目不超过 1000 。

思路

//TODO:其他思路

思路1

直接在原来的链表位置旁复制,然后遍历分离

代码

/*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/

class Solution {
    public Node copyRandomList(Node head) {
        if (head == null){
            return null;
        }
        
        Node pre = head;
        
        while(pre != null){
            Node newNode = new Node(pre.val);
            newNode.next = pre.next;
            pre.next = newNode;
            pre = pre.next.next;
        }
        
        pre = head;
        
        while(pre != null){
            if (pre.next != null && pre.random != null){
                pre.next.random = pre.random.next;
            } else {
                pre.next.random = null;
            }
            pre = pre.next.next;
        }
        
        Node origin = head;
        pre = head.next;
        Node result = head.next;
        
        while(pre != null){
            origin.next = origin.next.next;
            if (pre.next == null){
                pre.next = null;
            }else{
                pre.next = pre.next.next;
            }
            origin = origin.next;
            pre = pre.next;
        }
        
        return result;
    }
}

复杂度分析

思路1时间复杂度

$O(n)$

思路1空间复杂度分析

$O(1)$如果不算结果空间


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:141. 环形链表 Leetcode:141. 环形链表
Leetcode:141. 环形链表题目描述给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。 示例 1:输
2020-04-06
下一篇 
Leetcode:150. 逆波兰表达式求值 Leetcode:150. 逆波兰表达式求值
Leetcode:150. 逆波兰表达式求值题目描述根据逆波兰表示法,求表达式的值。 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 说明:整数除法只保留整数部分。 给定逆波兰表达式总是有
2020-04-05
  目录