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;
    }
};
相关推荐
Han.miracle1 分钟前
数据结构——排序的超级详解(Java版)
java·数据结构·学习·算法·leetcode·排序算法·1024程序员节
君鼎21 分钟前
C++通用业务标准库中常用接口函数总结
c++·1024程序员节
杨筱毅27 分钟前
【穿越Effective C++】条款5:了解C++默默编写并调用哪些函数——编译器自动生成的秘密
c++·effective c++·1024程序员节
落羽的落羽1 小时前
【Linux系统】从零掌握make与Makefile:高效自动化构建项目的工具
linux·服务器·开发语言·c++·人工智能·机器学习·1024程序员节
-森屿安年-1 小时前
STL 容器:List
开发语言·c++·list·1024程序员节
我搞slam1 小时前
插入区间--leetcode
算法·leetcode
前进之路91 小时前
Leetcode每日一练--40
算法·leetcode
uxiang_blog1 小时前
C++进阶:继承
开发语言·c++
Swift社区1 小时前
LeetCode 405 - 数字转换为十六进制数
算法·leetcode·职场和发展
赵杰伦cpp1 小时前
数据结构——二叉搜索树深度解析
开发语言·数据结构·c++·算法