C++速通LeetCode中等第20题-随机链表的复制(三步简单图解)

方法图解:

cpp 复制代码
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if ( !head ) {
            return nullptr;
        }
        Node *cur = head;
        // 1. 在原节点的每个节点后创建一个节点
        while ( cur ) {
            Node *newNode = new Node(cur -> val);
            newNode -> next = cur -> next;
            cur -> next = newNode;
            cur = cur -> next ->next;
        }

        // 2. 更新新节点的random指针
        cur = head;
        while ( cur ) {
            if ( cur -> random == nullptr ) {
                cur -> next -> random = nullptr;
            } else {
                cur -> next -> random = cur -> random -> next;
            }
            cur = cur -> next -> next;
        }

        // 3. 将两个链表拆开
        Node *dummy = new Node(-1);
        Node *curnew = dummy, *curold = head;
        while ( curold ) {
            curnew -> next = curold -> next;
            curnew = curnew -> next;
            curold->next = curnew->next;
            curold = curold -> next;
        }
        return dummy -> next;
    }
};
相关推荐
想吃火锅10052 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
王维同学2 小时前
进程模块枚举、映像身份与线程启动地址关联
c++·windows·安全
hold?fish:palm2 小时前
24 回文链表
数据结构·c++·链表
举手2 小时前
Dispatcher模块剖析
linux·c++
Nil2082 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
依然鸣3 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
库玛西5 小时前
现代 C++ 智能指针全景指南:从 RAII 思想到工业级实践
c语言·开发语言·c++·笔记·面试
liulilittle5 小时前
无锁并发容器的设计与实现原理
开发语言·c++·set·map·并发·无锁·lock-free
qeen876 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
Augustzero6 小时前
为什么线程不能说睡就睡?看懂等待与唤醒机制
c++·后端