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;
    }
};
相关推荐
不見星空14 分钟前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
米饭「」27 分钟前
C++AVL树
java·开发语言·c++
心愿许得无限大1 小时前
Qt 常用界面组件
开发语言·c++·qt
GiraKoo1 小时前
【GiraKoo】C++17的新特性
c++
Rockson1 小时前
C++如何查询实时贵金属行情
c++·api
shenyan~1 小时前
关于 c、c#、c++ 三者区别
开发语言·c++
mit6.8242 小时前
[vroom] docs | 输入与问题定义 | 任务与运输工具 | json
c++·自动驾驶
charlie1145141912 小时前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
chao_7894 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
GEEK零零七4 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode