Why i got runtime error here Last executed input: {-1,#}


  • 0
    W
        /**
     * 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::vector<RandomListNode* > array;
            RandomListNode * p = head;
            if(p == NULL) return NULL;
            while(p) {
                array.push_back(p);
                p = p->next;
            }
            RandomListNode * p1;
            p = head;
            RandomListNode * copyHead = new RandomListNode(p->label);
            copyHead->random = p;
            p1 = copyHead;
            p = p->next;
            while(p) {
                p1->next = new RandomListNode(p->label);
                p1 = p1->next;
                p1->random = p;
                p = p->next;
            }
            p1->next = NULL;
            p1 = copyHead;
            while(p1) {
                p1->random->next = p1;
                p1 = p1->next;
            }
            p1 = copyHead;
            while(p1) {
                p1->random = p1->random->random->next;
                p1 = p1->next;
            }
            p = head;
            if(array.size() == 1) {
                p->next = NULL;
                return copyHead;
            }
            int i = 1;
            for(; i < array.size(); ++i) {
                array[i-1]->next = array[i];
            }
            array[array.size()-1]->next = NULL;
            return copyHead;
        }
    };

Log in to reply
 

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