Find Intersection Point
Find the intersection point of two Y-shaped linked lists
Code
1def getIntersectionNode(headA, headB):2 # Calculate lengths of both lists3 lenA, lenB = 0, 04 currA, currB = headA, headB56 while currA:7 lenA += 18 currA = currA.next910 while currB:11 lenB += 112 currB = currB.next1314 # Reset pointers to heads15 currA, currB = headA, headB1617 # Move the longer list's pointer ahead18 if lenA > lenB:19 for _ in range(lenA - lenB):20 currA = currA.next21 elif lenB > lenA:22 for _ in range(lenB - lenA):23 currB = currB.next2425 # Move both pointers together26 while currA and currB:27 if currA == currB:28 return currA29 currA = currA.next30 currB = currB.next3132 return None
Function definition
Linked Lists
INIT LISTS
Step
0 / 10
Phase
Initialize
Diff
0
List A
List B
Progress
Processing
Searching for intersection point...
Pointer State
Pointers
pointerA
1
pointerB
5
lengthA
0
lengthB
0
Key Insight
Calculate lengths first, then align pointers to the same starting position before advancing both together.
Explanation
Init
Initialize Pointers
Set up pointers for both linked lists.