Naive C++ solution


  • 0
    Y
    class Solution {
    public:
        
        RandomListNode *copyRandomList(RandomListNode *head) {
            unordered_map<int, int> hash_label;
            unordered_map<int, RandomListNode*> hash_ptr;
            
            RandomListNode newHead(0);
            RandomListNode* p = &newHead;
            
            while (head) {
                RandomListNode* node = new RandomListNode(head->label);
                if (head->random)
                    hash_label[head->label] = head->random->label;
                hash_ptr[node->label] = node;
                
                p->next = node;
                p = p->next;
                head = head->next;
            }
            
            p = newHead.next;
            while (p) {
                if (hash_label.find(p->label) != hash_label.end()) {
                    int random_label = hash_label[p->label];    
                    p->random = hash_ptr[random_label];
                }
                p = p->next;
            }        
            return newHead.next;
        }
    };

Log in to reply
 

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