leetcode_138 随机链表的复制

1. 题意

就是复制链表,不过链表多了一个random指针,

它随机的指向链表中的元素,或者是一个空值。

2. 题解

如果是普通的链表,我们直接复制就好了,不过多了一个随机指针,它有可能指向后面的元素,因此我们可以用一个哈希表进行记录。

2.1 哈希表

有两种写法,一种是递归的。就是官方说的回溯。

cpp 复制代码
class Solution {
public:
    unordered_map<Node*, Node*> cachedNode;

    Node* copyRandomList(Node* head) {
        if (head == nullptr) {
            return nullptr;
        }
        if (!cachedNode.count(head)) {
            Node* headNew = new Node(head->val);
            cachedNode[head] = headNew;
            headNew->next = copyRandomList(head->next);
            headNew->random = copyRandomList(head->random);
        }
        return cachedNode[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) {
        
        Node *nHead = NULL;
        Node *pre   = NULL;

        map<Node *, Node *> pr;
        pr[NULL] = NULL;

        for (Node *cur = head; cur != NULL; cur = cur->next) {
            Node *ncur = new Node(cur->val);
            pr[cur] = ncur;
            
            if ( pre == NULL) {
                nHead = ncur;
            }
            else {
                pre->next = ncur;
            }
            pre = ncur;
        }

        for (Node *cur = head; cur != NULL; cur = cur->next ) {
            pr[cur]->random = pr[cur->random]; 
        }

        return nHead;
    }
};
2.2 奇偶链表

这种解法是在0x3f的题解里面看到的,

我自己感觉跟哈希表其实是一样的,

只是这里取了一下巧。

具体做法就是,把每一个复制的链表节点给链接到老链表的后面。

这样其实就可以通过next来实现和哈希表一样的功能了!

最后再把链表给断开就好了。

cpp 复制代码
class Solution {
public:
    Node* copyRandomList(Node* head) {
        
        Node *nxt = NULL;
        for (Node * cur = head; cur != NULL; cur = nxt) {
            nxt = cur->next;
            Node *nNode = new Node(cur->val);
            cur->next = nNode;
            nNode->next = nxt;
        }



        for (Node *cur = head; cur != NULL; cur = cur->next->next) {
            if ( cur->random != NULL) {
                cur->next->random = cur->random->next;
            }
        }



        Node *nHead = NULL;
        if (head)
            nHead = head->next;
        for (Node *cur = head; cur != NULL && cur->next != NULL; cur = nxt ) {
            nxt = cur->next;
            cur->next = nxt->next;
        }

        return nHead;
    }
};

3. 参考

leetcode
0x3f

相关推荐
BirdenT4 小时前
20260519紫题训练
c++·算法
csdn_aspnet9 小时前
C语言 Lomuto分区算法(Lomuto Partition Algorithm)
c语言·开发语言·算法
谙弆悕博士10 小时前
【附C源码】从零实现C语言堆数据结构:原理、实现与应用
c语言·数据结构·算法··数据结构与算法
gaosushexiangji13 小时前
DIC系统推荐:基于千眼狼三维数字图像相关的无人机旋翼疲劳试验全场应变与位移测量
人工智能·算法
小王C语言15 小时前
【线程概念与控制】:线程封装
jvm·c++·算法
圣保罗的大教堂15 小时前
leetcode 796. 旋转字符串 简单
leetcode
kyle~15 小时前
工程数学---点云配准卡布施(Kabsch)算法(求解最优旋转矩阵)
线性代数·算法·矩阵
张二娃同学15 小时前
03_变量常量与输入输出_printf与scanf详解
算法
Zhang~Ling16 小时前
深入解析C++list:从0到1实现一个完整的链表类
c++·链表·list
江南十四行16 小时前
并发编程(一)
java·jvm·算法