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;
    }
};
相关推荐
YuK.W27 分钟前
Leetcode100: 70.爬楼梯、118.杨辉三角、198.打家劫舍
java·算法·leetcode
Funing71 小时前
FreeRTOS学习day1:Keil 工程配置与 FreeRTOS 链表机制理解
数据结构·学习·链表
旖-旎2 小时前
《LeetCode 64 最小路径和 || LeetCode 174 地下城游戏》
c++·算法·leetcode·动态规划
凯瑟琳.奥古斯特3 小时前
力扣1009补码解法C++实现
开发语言·c++·算法·leetcode·职场和发展
Let's Chat Coding7 小时前
哈希算法:密码学的基础构件
算法·哈希算法
Tairitsu_H8 小时前
[LC优选算法#18] 前缀和 | 除⾃⾝以外数组的乘积 | 和为K的⼦数组 | 和可被K整除的⼦数组
算法·前缀和·哈希算法
凯瑟琳.奥古斯特8 小时前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
aqiu1111119 小时前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表
人道领域11 小时前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
Let's Chat Coding12 小时前
MAC 消息认证码:同时验证来源和完整性
算法·哈希算法