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;
    }
};
相关推荐
曦樂~2 小时前
Cpp面筋
c语言·c++
道尔柯南2 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
Dream it possible!5 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊6 小时前
算法之双指针系列(一)
算法·leetcode
十二6 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
Pniubi7 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH8 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi8 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
zjxtxdy9 小时前
C++面向对象程序开发-类与对象
开发语言·c++
東隅已逝,桑榆非晚11 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法