力扣:138.随机链表的复制

cpp 复制代码
class Solution {
public:
    Node* copyRandomList(Node* head) {
        if ( !head ) return nullptr;
        Node *cur = head;
        while ( cur ) {
            Node *copy = new Node( cur->val ); // 复制节点的值
            copy->next = cur->next, cur->next = copy, cur = copy->next; // 把复制的节点插在两个节点之间
        }
        cur = head;
        while ( cur ) {
            Node *copy = cur->next;
            copy->random = cur->random ? cur->random->next : nullptr; // 把复制的节点的 random 指针建立起来
            cur = copy->next;
        }
        cur = head;
        Node *newHead = head->next, *copyCur = newHead;
        while ( cur ) {
            cur->next = copyCur->next, cur = cur->next; // 拆分两个链表
            if ( cur ) copyCur->next = cur->next, copyCur = copyCur->next;
        }
        return newHead;
    }
};
  1. Node 有 3 个参数,val next 和 random
  2. 为了空间复杂度最优,在原来链表的节点之后插入一个节点,复制这个节点的 val next 和 random
相关推荐
Tisfy1 小时前
LeetCode 1927.求和游戏:抵消+看最值
java·leetcode·游戏·题解·博弈论
玖玥拾1 小时前
LeetCode 125 验证回文串
算法·leetcode
Asize8 小时前
146. LRU 缓存
算法
Asize8 小时前
543. 二叉树的直径
算法
lemon_sjdk8 小时前
ObjectProperty
java·开发语言·算法
Zentceh9 小时前
AI-ISP在夜视机芯中的应用:从传统ISP到PixelClean全彩夜视的进化
人工智能·科技·算法·计算机视觉·车载系统·视频·智能硬件
xier_ran9 小时前
【infra之路】AWQ 详解:激活感知权重保护,让 W4A16 量化精度超越 GPTQ
线性代数·算法·机器学习·量化·infra
亦皓ai9 小时前
AI时代后端工程(二):AI把代码写得越来越快,我却越来越不敢让它直接开工了
人工智能·算法·机器学习·搜索引擎·transformer
玖玥拾11 小时前
LeetCode 392 判断子序列
笔记·算法·leetcode
重生之后端学习12 小时前
239. 滑动窗口最大值[困难]✅
java·数据结构·算法·leetcode·职场和发展