Intersection of Two Linked Lists I C++ simple solution
// Elharem Soufiane
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        
        // Initialize two pointers pointer_A and pointer_B at the headA and headB.
        ListNode *pointer_A = headA, *pointer_B = headB;
        
        // If either of the nodes are null return NULL
        if(pointer_A == NULL || pointer_B == NULL) return NULL;
    
        // Traverse the list untill the intersection
        while(pointer_A != pointer_B){
            pointer_A = pointer_A->next;
            pointer_B = pointer_B->next;
            
            // If pointer_A meet pointer_B then it's the intersection node
            if(pointer_A == pointer_B) return pointer_A;
            
            // When pointer_A reaches the end of a list, then redirect it to the headB.
            if(pointer_A == NULL) pointer_A = headB;
            
            // When pointer_B reaches the end of a list, then redirect it to the headA.
            if(pointer_B == NULL) pointer_B = headA;
        }
        return pointer_A;
    }
};

Follow me on Github.

Comments (0)