Leetcode面试经典150题-138.随机链表的复制

题目比较简单,重点是理解思想,random不管,copy一定要放在next

而且里面的遍历过程不能省略

解法都在代码里,不懂就留言或者私信

java 复制代码
/*
// 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 {
    /**基本思路:1.遍历链表,每个节点拷贝一个节点放到它的next位置,然后它的copy的下一个放它原来的next
    2.把copy的random指针指向原始节点random指针的下一个(因为下一个是random的copy)
    3.拆分链表,把新的链表拷贝出来*/
    public Node copyRandomList(Node head) {
        if(head == null) {
            return null;
        }
        /**遍历链表复制节点并连接 */
        Node cur = head;
        while(cur != null) {
            Node next = cur.next;
            Node curCopy = new Node(cur.val);
            cur.next = curCopy;
            curCopy.next = next;
            cur = next;
        }
        /**设置新节点的random指针*/
        cur = head;
        while(cur != null) {
            /**这里因为存在复制节点并且复制节点肯定放在原始节点的下一个,所以
            cur.next肯定不为空,所以这里不会有空指针的问题*/
            Node next = cur.next.next;
            cur.next.random = cur.random == null? null : cur.random.next;
            cur = next;
        }
        /**断开链接,分离出拷贝链表,这里先把拷贝链表头节点拿出来*/
        Node newHead = head.next;
        /**还是通过从原来的头开始遍历,因为原链表要改next指针 */
        cur = head;
        while(cur != null) {
            /**拿到原来链表中的next,这个next可能为空 */
            Node next = cur.next.next;
            /**这里有可能next是null,要判断,不然会有空指针 */
            cur.next.next = next == null? null : next.next;
            /**指向原来的next */
            cur.next = next;
            /**指针挪到下个节点继续 */
            cur = next;
        }
        return newHead;
        
    }
}
相关推荐
i嗑盐の小F3 分钟前
【 ACM独立出版,见刊后1个月检索!!!】第二届通信网络与机器学习国际学术会议(CNML 2024,10月25-27)
网络·图像处理·人工智能·深度学习·算法·机器学习·计算机视觉
oliveira-time21 分钟前
C++ prime plus课后习题-第二章
开发语言·c++·算法
Chase-Hart1 小时前
【每日一题】LeetCode 7.整数反转(数学)
java·数据结构·算法·leetcode·eclipse
guangzhi06331 小时前
JVM本地方法栈
java·jvm·面试
IT枫斗者1 小时前
集合工具类
java·linux·数据库·windows·算法·microsoft
朱皮皮呀2 小时前
排序算法-归并排序
数据结构·算法·排序算法·归并排序
MogulNemenis2 小时前
力扣100题——贪心算法
算法·leetcode·贪心算法
aWty_2 小时前
机器学习--线性回归
python·算法·机器学习·线性回归
我搞slam2 小时前
Cartographer源码理解
算法·slam·cartographer
SEU-WYL4 小时前
基于深度学习的因果发现算法
人工智能·深度学习·算法