Sharing my very straightforward and concise solution


  • 0
    Z
    RandomListNode *copyRandomList(RandomListNode *head) {
        if(head == nullptr){
            return nullptr;
        }
        unordered_map<RandomListNode*, RandomListNode*> map;
        RandomListNode* result = new RandomListNode(head->label);
        map[head] = result;
        RandomListNode* p1 = head->next;
        RandomListNode* p2 = result;
        while(p1 != nullptr){
            p2->next = new RandomListNode(p1->label);
            p2 = p2->next;
            map[p1] = p2;
            p1 = p1->next;
        }
        p1 = head;
        p2 = result;
        while(p1 != nullptr){
            p2->random = map[p1->random];
            p1 = p1->next;
            p2 = p2->next;
        }
        return result;
    }
    

    I use two loops to finish this task.

    The first loop is to create a new linked list.

    The second loop is to set value to "random" pointer with help of a hash table.


Log in to reply
 

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