Intersection of Two Linked Lists


Card image cap

None

Credit: Image Source


/**
 * 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) {

        int l1 = 0;
        int l2 = 0;

        ListNode *tmp1, *tmp2;
        tmp1 = headA;
        tmp2 = headB;

        while(tmp1 != NULL){
            l1 += 1;
            tmp1 = tmp1->next;
        }

        while(tmp2 != NULL){
            l2 += 1;
            tmp2 = tmp2->next;
        }

        tmp1 = headA;
        tmp2 = headB;

        if(l1 > l2){
            int diff = l1-l2;
            while(diff > 0){
                tmp1 = tmp1->next;
                diff -= 1;
            }
        }

        if(l2 > l1){
            int diff = l2-l1;
            while(diff > 0){
                tmp2 = tmp2->next;
                diff += -1;
            }
        }


        while(tmp1 != NULL && tmp2 != NULL){
            if(tmp1 == tmp2) return tmp1;
            tmp1 = tmp1->next;
            tmp2 = tmp2->next;
        }

        return NULL;
        
    }
};

Comments