My c++ code using cycle list, but MLE


  • 0
    L

    make listB a cycle, and then find the begin of the cycle.but i have a MLE problem, i do not know why

    class Solution{
        public:
            ListNode* getIntersectionNode(ListNode* headA, ListNode *headB){
                if(headA == nullptr || headB == nullptr) return NULL;
                ListNode* tail = headB;
                while(tail->next != nullptr){
                    tail = tail->next;
                }
                if(headA->next == nullptr)
                    if (headA == tail) return headA;
                    else return NULL;
                tail->next = headB;
                ListNode* slow = headA;
                ListNode* fast = headA;
                do{
                    if(slow == nullptr || fast->next == nullptr) return NULL;
                    else{slow = slow->next;
                        fast = fast->next->next;}
                }while(fast != slow && fast != NULL && slow != NULL);
                if(fast == nullptr || slow == nullptr) return NULL;
                slow = headA;
                while(fast != slow){
                    fast = fast->next;
                    slow = slow->next;
                }
                tail->next = NULL;
                return slow;
            }
        };

  • 1
    S

    You must make sure the connectivity of the linked structure is restored by calling 'tail->next = NULL' at EVERY exit (marked by the 'return' statement) of the function. Currently, your code contains FOUR returns after the structure is modified, but you only try to restore the structure before ONE of them.


  • 0
    L

    thanks a lot. :) it is a stupid mistake. actually, i should make the function exit very clearly, not meaning the end of the func.


Log in to reply
 

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