Given: Heads of two singly linked lists.
Return: The node where the two lists intersect (by reference), or None if they don’t intersect.
How It Works:
-
Two pointers start at
headAandheadB. -
When a pointer reaches the end of its list, it switches to the head of the other list.
-
If the two lists intersect, they’ll meet at the intersection node.
-
If not, both will end up as
Noneat the same time.
Time & Space Complexity:
-
Time: O(m + n)
-
Space: O(1)
def find_intersecting(heada,headb):
if not heada or not headb:
return None
currentA = heada
currentB = headb
while currentA != currentB:
if currentA:
currentA = currentA.next
else:
currentA = headb
if currentB:
currentB = currentB.next
else:
currentB = heada
return currentA # Either the intersecting node or None
How It Works:
-
ptrAandptrBare two pointers, initially starting atheadAandheadBrespectively. -
They traverse the lists node by node.
-
When a pointer reaches the end of its list, it is redirected to the start of the other list.
-
This ensures that both pointers travel the same total distance, and thus will meet at the intersection point — or both become
Noneif no intersection.
List A: A1 → A2
↘
C1 → C2 → C3
↗
List B: B1 → B2 → B3