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;
    }
};
相关推荐
禹中一只鱼35 分钟前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒36 分钟前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
crescent_悦1 小时前
C++:The Largest Generation
java·开发语言·c++
paeamecium2 小时前
【PAT甲级真题】- Student List for Course (25)
数据结构·c++·算法·list·pat考试
c++逐梦人4 小时前
C++11——— 包装器
开发语言·c++
十年编程老舅5 小时前
Linux 多线程高并发编程:读写锁的核心原理与底层实现
linux·c++·linux内核·高并发·线程池·多线程·多进程
wildlily84275 小时前
C++ Primer 第5版章节题 第十三章(二)
开发语言·c++
xiaoye-duck6 小时前
【C++:unordered_set和unordered_map】 深度解析:使用、差异、性能与场景选择
开发语言·c++·stl
_日拱一卒6 小时前
LeetCode:滑动窗口的最大值
数据结构·算法·leetcode
老约家的可汗6 小时前
list 容器详解:基本介绍与常见使用
c语言·数据结构·c++·list