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;
    }
};
相关推荐
bcbobo21cn12 分钟前
MFC获取网页的html文本
c++·mfc·chttpfile
一丝晨光16 分钟前
语言的循环语句
java·c++·python·c#·c·fortran·algol
hn小菜鸡30 分钟前
LeetCode 面试经典150题 67.二进制求和
算法·leetcode·面试
刘好念30 分钟前
[OpenGL]使用OpenGL绘制带纹理三角形
c++·计算机图形学·opengl
为啥不吃肉捏1 小时前
C++/Qt 集成 AutoHotkey
开发语言·c++·qt
努力学习的小廉1 小时前
【C++】—— string模拟实现
开发语言·c++
小灰灰爱代码1 小时前
C++——求3*3矩阵主对角元素之和。
c++·算法·矩阵
鱼跃鹰飞1 小时前
Leetcode面试经典150题-94.二叉树的中序遍历
算法·leetcode·面试
hjxxlsx2 小时前
插入与冒泡排序(C++)
c++·算法·排序算法
Mephisto.java2 小时前
【力扣 | SQL题 | 每日三题】力扣175, 176, 181
sql·算法·leetcode