LeetCode 138 Copy List with Random Pointer

Posted Shendu.cc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 138 Copy List with Random Pointer相关的知识,希望对你有一定的参考价值。

LeetCode 138. Copy List with Random Pointer

又是copy 指针的题目。

这个和上一道题目有个坑点,函数中的参数要加&地址符。

class Solution {
public:
    RandomListNode* ans;
    map<int,RandomListNode*> m;
    RandomListNode *copyRandomList(RandomListNode *head) {
        
       if(head==NULL)
           return ans;
       
        dfs(ans,head);
        return ans;
    }
    
    void dfs(RandomListNode* &ans,RandomListNode *head)
    {
        if(head==NULL) return;
        if(m[head->label]==NULL)
        {
             m[head->label] = new RandomListNode(head->label);
        }
        ans = new RandomListNode(head->label);
        if(head->random==NULL)
            ans->random = NULL;
        else
        {
            if(m[head->random->label]==NULL)
                m[head->random->label] = new RandomListNode(head->random->label);
            ans->random = m[head->random->label];
        }

        dfs(ans->next,head->next);
    }
};

以上是关于LeetCode 138 Copy List with Random Pointer的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 138. Copy List with random pointer

LeetCode-138-Copy List with Random Pointer

Leetcode 138. Copy List with Random Pointer

LeetCode 138. Copy List with Random Pointer

[LeetCode] 138. Copy List with Random Pointer

leetcode 138. Copy List with Random Pointer ----- java