To find the intersection node of two
linked lists, we use a two-pointer technique. We
initialize two pointers, 'a' and 'b', at the heads of the two lists.
We
traverse
both lists
simultaneously. When one pointer
reaches the end
of its
list, it is
redirected
to the
head of the other list
.
This ensures that both pointers
traverse the same number
of nodes
before meeting at the intersection point.
If there is no intersection, both pointers will eventually be NULL, and the loop will terminate.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode tmpA = headA; ListNode tmpB = headB; while(headA!=headB){ if(headA==null) headA = tmpB; else headA = headA.next; if(headB == null) headB = tmpA; else headB = headB.next; } return headA; } }
The algorithm traverses both linked lists once, where 'm'
and
'n'
are the
lengths of the two lists.
The algorithm uses only two pointers, ensuring constant space usage.