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;
    }
};
相关推荐
We་ct29 分钟前
LeetCode 73. 矩阵置零:原地算法实现与优化解析
前端·算法·leetcode·矩阵·typescript
好学且牛逼的马34 分钟前
【Hot100|22-LeetCode 206. 反转链表 - 完整解法详解】
算法·leetcode·矩阵
v_for_van40 分钟前
力扣刷题记录3(无算法背景,纯C语言)
c语言·算法·leetcode
心.c1 小时前
Vue3+Node.js实现文件上传分片上传和断点续传【详细教程】
前端·javascript·vue.js·算法·node.js·哈希算法
We་ct1 小时前
LeetCode 48. 旋转图像:原地旋转最优解法
前端·算法·leetcode·typescript
爱尔兰极光1 小时前
LeetCode--长度最小的子数组
算法·leetcode·职场和发展
有一个好名字1 小时前
力扣-电话号码组合
算法·leetcode·职场和发展
鱼跃鹰飞1 小时前
Leetcode会员尊享面试100题:1086:前五科的均分
算法·leetcode·职场和发展
sin_hielo1 小时前
leetcode 3010
数据结构·算法·leetcode
TracyCoder12311 小时前
LeetCode Hot100(19/100)——206. 反转链表
算法·leetcode