The following is the definition of a linked list node.
class ListNode:
def __init__(self, data: int = 0, next: ListNode | None = None):
self.data = data
self.next = next
public class ListNode {
int data;
ListNode next;
ListNode() {
this(0, null);
}
ListNode(final int x) {
this(x, null);
}
ListNode(final int data, final ListNode next) {
this.data = data;
this.next = next;
}
}
The following is the implementation of the solution in Python / Java.
class Solution:
def getIntersectionNode(
self, h1: ListNode | None, h2: ListNode | None
) -> ListNode | None:
# If either of the linked list points to an empty list
# then there can be no intersecation, do an early return
if h1 is None or h2 is None:
return None
# Copy two head pointers of the linked lists into temporary variables
p1, p2 = h1, h2
while p1 != p2:
p1 = p1.next
p2 = p2.next
# This check is needed for two equal length linked lists
# otherwise both will reach null together and get reset to
# the other linked list's head, creating an infinite loop
if p1 == p2:
break
# Whichever pointer hits null value first, put that to the
# head of the other linked list, essentially the idea is to
# ensure both travel equal distant, so then converge on the
# common first node together
if p1 is None:
p1 = h2
if p2 is None:
p2 = h1
# It is very much possible that the two linked lists do not have
# anything common at all, in that case, both will reach null together
# in the second iteration, and the equality check will break the while
# loop, so both pointers will have null, and return value will be null
return p1
public class Solution {
public ListNode getIntersectionNode(final ListNode h1, final ListNode h2) {
if (null == h1 || null == h2) {
return null;
}
ListNode p1 = h1;
ListNode p2 = h2;
while (p1 != p2) {
p1 = p1.next;
p2 = p2.next;
if (p1 == p2) {
break;
}
if (null == p1) {
p1 = h2;
}
if (null == p2) {
p2 = h1;
}
}
return p1;
}
}