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;
        
    }
}
相关推荐
kyriewen5 分钟前
事件流与事件委托:当点击按钮时,浏览器里发生了什么?
前端·javascript·面试
数据皮皮侠6 分钟前
2285 上市公司组织衰退程度【Dec】2010-2024
大数据·人工智能·算法·制造
不秃不少年6 分钟前
工厂方法模式(Factory Method)
java·面试·工厂方法模式
daxi1508 分钟前
C语言从入门到进阶——第17讲:字符串函数
c语言·开发语言·算法·蓝桥杯
AY呀9 分钟前
# 从手写 debounce 到企业级实现:我在面试中如何“降维打击”面试官
前端·面试
wljy111 分钟前
第十四届蓝桥杯大赛软件赛省赛C/C++ 大学 B 组(个人见解,已完结)
c语言·c++·算法·蓝桥杯
CoderCodingNo14 分钟前
【GESP】C++八级考试大纲知识点梳理 (7) 算法的时间和空间效率分析
开发语言·c++·算法
青瓷程序设计18 分钟前
基于YOLO的安全帽佩戴检测系统~Python+模型训练+2026原创+YOLO算法
python·算法·yolo
Trouvaille ~19 分钟前
【优选算法篇】拓扑排序——逻辑先后与任务依赖的终极拆解
数据结构·c++·算法·leetcode·青少年编程·蓝桥杯·拓扑学
T1an-122 分钟前
博乐科技笔试题
科技·算法