sundeepblue
4/12/2014 - 5:03 AM

Find if the two linked lists intersect. Solution should not use extra memory

Find if the two linked lists intersect. Solution should not use extra memory

bool is_intersect(ListNode *h1, ListNode *h2) {
    if(!h1 || !h2) return false;
    if(h1 == h2) return true;
    int len1 = 0, len2 = 0;
    for(ListNode *p1 = h1; p1; p1 = p1->next) len1++;
    for(ListNode *p2 = h2; p2; p2 = p2->next) len2++;
    //if(len1 == len2)  // equal length may still intersect! so this checking is wrong.
    //    return false;
    ListNode *p = len1 > len2 ? h1 : h2;
    ListNode *q = len1 > len2 ? h2 : h1;
    int diff = abs(len1 - len2);
    while(diff-- != 0) p = p->next;
    while(p && q) {
        if(p == q) return true;
        p = p->next;
        q = q->next;
    }
    return false;
}