73 ms c++ solution


  • 0
    P
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            int s1 = getLen(headA);
            int s2 = getLen(headB);
            if (headA == NULL || headB == NULL) {
                return NULL;
            }
            moveHead(s1-s2, headA);
            moveHead(s2-s1, headB);
    
            while(headA != headB) {
                headA = headA->next;
                headB = headB->next;
            }
            
            return headA==headB ? headA : NULL;
        }
        
        inline int getLen(ListNode* n) {
            int i = 0;
            while(n) {
                n = n->next;
                i++;
            }
            return i;
        }
        
        inline void moveHead(int i, ListNode*& n) {
            while(i > 0 && n) {
                n = n->next;
                i--;
            }
        }
    };

Log in to reply
 

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