My 52 ms C++ code


  • 0
    Z
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            if(headA == NULL || headB == NULL) return NULL;
            int lena = 1;
            ListNode *pa = headA;
            while(pa->next)
            {
                pa=pa->next; ++lena;
            }
            int lenb = 1;
            ListNode *pb = headB;
            while(pb->next)
            {
                pb=pb->next;
                ++lenb;
            }
            if(pa!=pb) return NULL;/// check end node 
            
            int dif = abs(lena-lenb);
            if(lena>lenb)
            {
                while(dif-->0)
                headA=headA->next;
            }
            else
            {
                while(dif-->0)
                headB=headB->next;
            }
            
            while(headA && headB && headA!=headB)
            {
                headA=headA->next;
                headB=headB->next;
            }
            return headA;
            
            
        }
    };

Log in to reply
 

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