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;
    }
};
相关推荐
hai_qin11 分钟前
十三,数据结构-树
数据结构·c++
和光同尘@1 小时前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_021 小时前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_991 小时前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
@areok@1 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言2 小时前
【C++进阶】---- map和set的使用
开发语言·c++
Elnaij2 小时前
从C++开始的编程生活(8)——内部类、匿名对象、对象拷贝时的编译器优化和内存管理
开发语言·c++
我爱996!2 小时前
LinkedList与链表
数据结构·链表
liuyao_xianhui3 小时前
内存管理(C/C++)
java·开发语言·c++
饭碗的彼岸one3 小时前
C++设计模式之单例模式
c语言·开发语言·c++·单例模式·设计模式·饿汉模式·懒汉模式