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;
    }
};
相关推荐
电子_咸鱼3 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫3 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
微笑尅乐6 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
im_AMBER6 小时前
算法笔记 05
笔记·算法·哈希算法
夏鹏今天学习了吗7 小时前
【LeetCode热题100(46/100)】从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
吃着火锅x唱着歌7 小时前
LeetCode 2389.和有限的最长子序列
算法·leetcode·职场和发展
保持低旋律节奏7 小时前
C++——list链表
c++·链表·list
.YM.Z9 小时前
数据结构——链表(二)
数据结构·链表
一只鱼^_10 小时前
第 167 场双周赛 / 第 471 场周赛
数据结构·b树·算法·leetcode·深度优先·近邻算法·迭代加深
老K的Java兵器库12 小时前
Collections 工具类 15 个常用方法源码:sort、binarySearch、reverse、shuffle、unmodifiableXxx
java·开发语言·哈希算法