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;
    }
};
相关推荐
蒙奇D索大2 小时前
【算法】递归算法的深度实践:从布尔运算到二叉树剪枝的DFS之旅
笔记·学习·算法·leetcode·深度优先·剪枝
卡提西亚3 小时前
C++笔记-25-函数模板
c++·笔记·算法
R&L_201810014 小时前
C++之内联变量(Inline Variables)
c++·c++新特性
小白程序员成长日记4 小时前
2025.11.10 力扣每日一题
数据结构·算法·leetcode
IT阳晨。5 小时前
【QT开发】交叉编译QT程序在ARMLinux平台上运行
c++·qt·交叉编译·armlinux·代码移植
派大星爱吃猫5 小时前
C++隐藏的this指针(详解)
c++·this指针
虾..5 小时前
C++ 哈希
开发语言·c++·哈希算法
liu****5 小时前
14.日志封装和线程池封装
linux·开发语言·c++
将编程培养成爱好5 小时前
C++ 设计模式《统计辅助功能》
开发语言·c++·设计模式·访问者模式
dragoooon346 小时前
[优选算法专题六.模拟 ——NO.40~41 外观数列、数青蛙]
数据结构·算法·leetcode