LeetCode:随机链表的复制

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 {
    public Node copyRandomList(Node head) {
        //null判断
        if(head  == null){
            return null;
        }
        //制造分身
        Node curr = head;
        while(curr != null){
            Node clone = new Node(curr.val);
            clone.next = curr.next;
            curr.next = clone;
            curr = clone.next;
        }
        //复制random指针
        curr = head;
        while(curr != null){
            if(curr.random != null){
                curr.next.random = curr.random.next;
            }
            curr = curr.next.next;
        }
        //分离链表
        curr = head;
        Node cloneHead = head.next;
        Node cloneCurr = cloneHead;
        while(curr != null){
            curr.next = curr.next.next;

            if(cloneCurr.next != null){
                cloneCurr.next = cloneCurr.next.next;
            }

            curr = curr.next;
            cloneCurr = cloneCurr.next;
        }
        return cloneHead;
    }
}

先复制一份相同的节点,指向为A->A'->B->B';

然后将random指针也复制一份;

最后将两组指针进行分离。

相关推荐
lisw0518 小时前
稀疏算法概述!
算法·机器人·无人机
YLCHUP19 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴20 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu1 天前
python:Logistic Regression
开发语言·后端·python·算法
geovindu1 天前
python: Random Forest
开发语言·后端·python·算法·随机森林
凌冰_1 天前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏1 天前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
饮水桶_T1 天前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博
饮水桶_T1 天前
Java调用大语言模型、多轮对话 笔记
笔记·算法·设计模式·电脑·ai编程
AAA修煤气灶刘哥1 天前
QQ 音乐怎么在 25 毫秒内,决定一句话该交给谁?
人工智能·算法·llm