AlgoMaster Logo

Intersection of Two Linked Lists

listA=[4, 1],listB=[5, 6, 1],intersection=[8, 4, 5]
1public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
2    if (headA == null || headB == null) return null;
3
4    ListNode pA = headA;
5    ListNode pB = headB;
6
7    while (pA != pB) {
8        // Move pA: if at end, switch to headB
9        pA = (pA == null) ? headB : pA.next;
10        // Move pB: if at end, switch to headA
11        pB = (pB == null) ? headA : pB.next;
12    }
13
14    return pA; // Either intersection or null
15}
0 / 31
41561845headAheadB
DSA Animation | AlgoMaster.io | AlgoMaster.io