Straightforward hash map based C++ solution


  • 0
    class Solution {
    private:
        RandomListNode* deepcopy( RandomListNode* head, unordered_map<RandomListNode*, RandomListNode*>& copied ) {
            if ( !head ) return NULL;
            if( copied.find(head) != copied.end() ) return copied[head];
            copied[head] = new RandomListNode( head->label );
            if( head->next ) copied[head]->next = deepcopy( head->next, copied );
            if( head->random ) copied[head]->random = deepcopy( head->random, copied );
            return copied[head];
        }
    public:
        RandomListNode *copyRandomList(RandomListNode *head) {
            unordered_map<RandomListNode*, RandomListNode*> copied;
            return deepcopy( head, copied );
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.