Leetcode 138. Copy List with Random Pointer

Posted randyniu

tags:

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

/**
 * Definition for singly-linked list with a random pointer.
 * struct RandomListNode {
 *     int label;
 *     RandomListNode *next, *random;
 *     RandomListNode(int x) : label(x), next(NULL), random(NULL) {}
 * };
 */
class Solution {
public:
    RandomListNode *copyRandomList(RandomListNode *head) {
        std::map<RandomListNode *, int> node_map;
        std::vector<RandomListNode *> node_vec;
        RandomListNode * ptr = head;
        int i=0;
        while(ptr)
        {
            node_vec.push_back(new RandomListNode(ptr->label));
            node_map.insert(make_pair(ptr, i));
            ptr = ptr->next;
            ++i;
        }
        node_vec.push_back(0);
        ptr = head;
        i = 0;
        while(ptr)
        {
            node_vec[i]->next = node_vec[i+1];
            if(ptr->random)
            {
                int id = node_map[ptr->random];
                node_vec[i]->random = node_vec[id];
            }
            ptr = ptr->next;
            i++;
        }
        return node_vec[0];
    }
};

这个是借助了映射的概念,用了额外的存储空间,其实可以不用额外的存储空间,将新节点增添到对应节点的后面,这样统一进行操作就方便了。

以上是关于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