Simple C++ code (apparently beats 96%)


  • 0
    G
        // Insert new nodes in between the nodes of the given list, set random pointers and split the lists
        RandomListNode *copyRandomList(RandomListNode *head) {
            typedef RandomListNode RLNode;
            RLNode* t_head = head;
            while (t_head) {
                RLNode* temp = new RLNode(t_head->label);
                temp->next = t_head->next;
                t_head->next = temp;
                t_head = temp->next;
            }
    
            t_head = head;
            while (t_head) {
                t_head->next->random = t_head->random ? t_head->random->next : NULL;
                t_head = t_head->next->next;
            }
            
            RLNode* ret_head = NULL, *t_ret_head = NULL;
            t_head = head;
            while (t_head) {
                t_ret_head = t_head->next;
                if (!ret_head) {
                    ret_head = t_ret_head;
                }
                t_head->next = t_ret_head->next;
                t_head = t_head->next;
                t_ret_head->next = t_head ? t_head->next : NULL;
            }
            
            return ret_head;
        }
    

Log in to reply
 

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