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;
    }
};
相关推荐
栈与堆23 分钟前
LeetCode 19 - 删除链表的倒数第N个节点
java·开发语言·数据结构·python·算法·leetcode·链表
努力学算法的蒟蒻1 小时前
day58(1.9)——leetcode面试经典150
算法·leetcode·面试
txinyu的博客1 小时前
map和unordered_map的性能对比
开发语言·数据结构·c++·算法·哈希算法·散列表
im_AMBER2 小时前
Leetcode 101 对链表进行插入排序
数据结构·笔记·学习·算法·leetcode·排序算法
予枫的编程笔记2 小时前
【Java集合】深入浅出 Java HashMap:从链表到红黑树的“进化”之路
java·开发语言·数据结构·人工智能·链表·哈希算法
踩坑记录2 小时前
leetcode hot100 560.和为 K 的子数组 medium 前缀和 + 哈希表
leetcode
独自破碎E3 小时前
【队列】按之字形顺序打印二叉树
leetcode
AlenTech3 小时前
206. 反转链表 - 力扣(LeetCode)
数据结构·leetcode·链表
踩坑记录3 小时前
leetcode hot100 438. 找到字符串中所有字母异位词 滑动窗口 medium
leetcode·职场和发展
YuTaoShao4 小时前
【LeetCode 每日一题】1458. 两个子序列的最大点积——(解法三)状态压缩
算法·leetcode·职场和发展