Leetcode 138. 随机链表的复制 哈希 / 拼接+拆分

原题链接:添加链接描述



哈希:

cpp 复制代码
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head==NULL) return NULL;
        Node* cur = head;
        unordered_map<Node*,Node*> mp;
        while(cur!=NULL){
            mp[cur]=new Node(cur->val);
            cur=cur->next;
        }
        cur = head;
        while(cur!=NULL){
            mp[cur]->next = mp[cur->next];
            mp[cur]->random = mp[cur->random];
            cur=cur->next;
        }
        return mp[head];
    }
};

拼接+拆分:

cpp 复制代码
/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;
    
    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if(head==NULL) return NULL;
        Node* cur = head;
        while(cur!=NULL){
            Node* cur_copy = new Node(cur->val);
            cur_copy->next = cur->next;
            cur_copy->random = NULL;
            cur->next = cur_copy;
            cur = cur_copy->next;
        }
        cur = head;
        while(cur!=NULL){
            Node* random = cur->random;
            Node* cur_copy = cur->next;
            if(random!=NULL) cur_copy->random = random->next;
            cur = cur_copy->next;
        }
        Node* node = head->next;
        Node* pre = node;
        int cnt=0;
        cur = head;
        while(cur!=NULL){
            Node* cur_copy = cur->next;
            cur->next = cur_copy->next;
            if(cnt){
                pre->next = cur_copy;
                pre= cur_copy;
            }
            cnt++;
            cur = cur->next;
        }
        return node;
    }
};
相关推荐
abcefg_h2 小时前
链表算法---基本算法操作(go语言版)
算法·链表·golang
孙同学_3 小时前
面试题 16.25. LRU 缓存
leetcode·缓存
小白程序员成长日记4 小时前
2025.11.09 力扣每日一题
算法·leetcode·职场和发展
7澄14 小时前
深入解析 LeetCode 1572:矩阵对角线元素的和 —— 从问题本质到高效实现
java·算法·leetcode·矩阵·intellij-idea
程序员东岸5 小时前
数据结构精讲:从栈的定义到链式实现,再到LeetCode实战
c语言·数据结构·leetcode
z1874610300317 小时前
list(带头双向循环链表)
数据结构·c++·链表
sin_hielo17 小时前
leetcode 1611
算法·leetcode
来荔枝一大筐18 小时前
C++ LeetCode 力扣刷题 541. 反转字符串 II
c++·算法·leetcode
小白程序员成长日记19 小时前
2025.11.07 力扣每日一题
数据结构·算法·leetcode
·白小白19 小时前
力扣(LeetCode) ——209. 长度最小的子数组(C++)
c++·算法·leetcode