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

相关推荐
W_chuanqi6 分钟前
RDEx:一种效果驱动的混合单目标优化器,自适应选择与融合多种算子与策略
人工智能·算法·机器学习·性能优化
L_090720 分钟前
【Algorithm】二分查找算法
c++·算法·leetcode
靠近彗星23 分钟前
3.3栈与队列的应用
数据结构·算法
while(1){yan}2 小时前
数据结构之链表
数据结构·链表
Han.miracle4 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8246 小时前
前后缀分解
算法
独自破碎E7 小时前
判断链表是否为回文
数据结构·链表
你好,我叫C小白7 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林9 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway10 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器