请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 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 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof

由于是一个复制链表,那么即使是链表中只有一个节点,都需要进行复制。其次,如果链表是一个空链表,那么就直接返回null。

解题思路:复制 + 拆分
1、复制next节点,从而实现类似下图的形式:
在这里插入图片描述
2、拆分节点,将一条链表拆成两条相同的链表。请看下图:
在这里插入图片描述
对应的代码:

/*
// 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) //这里不可以些if(head == null || head.next == null),然后返回head,否则会发生报错的
           return null;//如果链表为空,那么直接返回null
        Node cur = head;
        //复制next指针域
        while(cur != null){
            Node node = new Node(cur.val); //构建和当前节点的值相等的节点,同时next和random初始化为null
            node.next = cur.next;
            cur.next = node;
            cur = cur.next.next;//移动两步,如果是cur = cur.next写的话,那么下一次的cur就是刚刚复制的node
        }
        //复制random
        cur = head;
        while(cur != null){
            if(cur.random != null){
                //必须有这一步,如果没有,那么可能会因为cur.random.next报NullPointerException
                cur.next.random = cur.random.next;
            }
            cur = cur.next.next;//同样移动两步
        }
        cur = head.next;
        Node pre = head,res = head.next;//res存放第二个节点(因为这个节点是复制链表的头结点,最后将res返回即可)
        while(cur.next != null){
            //如果没有遍历到最后一个节点,那么继续操作
            pre.next = pre.next.next;
            cur.next = cur.next.next;
            cur = cur.next;
            pre = pre.next;
        }
        //当退出循环的时候,cur处在最后一个节点,而pre在倒数第二节点,还需要将最后一个节点删除,才可以保持原来的链表的样子
        pre.next = null;
        return res;
       
    }
}

运行结果:
在这里插入图片描述

值得注意的是,在进行拆分操作的时候,不可以这样写:

主要区别是在于cur.next = cur.next.next和pre.next = pre.next.next的先后顺序问题。这样写的话,过程应该是一样的,但是提交测试的时候却发现报错了:
在这里插入图片描述
错误的代码:

cur = head.next;
        Node pre = head,res = head.next;//res存放第二个节点(因为这个节点是复制链表的头结点,最后将res返回即可)
        while(cur.next != null){
            //如果没有遍历到最后一个节点,那么继续操作
            cur.next = cur.next.next;
            pre.next = pre.next.next;
            cur = cur.next;
            pre = pre.next;
        }
        //当退出循环的时候,cur处在最后一个节点,而pre在倒数第二节点,还需要将最后一个节点删除,才可以保持原来的链表的样子
        pre.next = null;

其实这个答案很简单,如果执行cur.next = cur.next.next,那么就会导致pre.next.next是一个空指针,所以没有办法执行pre.next = pre.next.next,从而导致错误。如果还没有清楚,请看下面的图解:
在这里插入图片描述

更多推荐