I got runtime error by change one line, but idk why


  • 0
    A
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            
                int lenA = 0, lenB = 0;
                ListNode* curA = headA;
                ListNode* curB = headB;
                
                while(curA){ ++lenA; curA = curA->next; }
                while(curB){ ++lenB; curB = curB->next; }
                
                //for(int i = 0; i < abs(lenA - lenB); i++) //use this might runtime error
                for(int i = abs(lenA - lenB); i > 0; i--) //AC
                {
                    if(lenA < lenB) headB = headB->next;
                    else
                        headA = headA->next;
                }
                
                while(headA && headB)
                {
                    if(headA == headB) return headA;
                    else
                    {
                        headA = headA->next;
                        headB = headB->next;
                    }
                }
        }
    };
    

    You can see the comment in the code, the solution idea is simple.
    Just try to make these two lists head alignment then find out the intersection.


Log in to reply
 

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