class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def get_length(head):
length = 0
current = head
while current:
length += 1
current = current.next
return length
def get_intersection_node(headA, headB):
lenA = get_length(headA) # get length of list A
lenB = get_length(headB) # get length of list B
# Align start pointers
currA, currB = headA, headB
if lenA > lenB:
for _ in range(lenA - lenB):
currA = currA.next # advance longer list pointer
else:
for _ in range(lenB - lenA):
currB = currB.next # advance longer list pointer
# Move both pointers until they meet or reach end
while currA and currB:
if currA == currB:
return currA # intersection found
currA = currA.next # move forward
currB = currB.next # move forward
return None # no intersection
# Driver code to create lists and test
# Shared part
shared = ListNode(7, ListNode(8))
# List A: 1->2->3->7->8
headA = ListNode(1, ListNode(2, ListNode(3, shared)))
# List B: 4->5->7->8
headB = ListNode(4, ListNode(5, shared))
intersection = get_intersection_node(headA, headB)
if intersection:
# Print from intersection to end
curr = intersection
result = []
while curr:
result.append(str(curr.val))
curr = curr.next
print(" -> ".join(result) + " -> null")
else:
print("No intersection")lenA = get_length(headA) # get length of list A
calculate length of first list
lenB = get_length(headB) # get length of list B
calculate length of second list
if lenA > lenB:
for _ in range(lenA - lenB):
currA = currA.next # advance longer list pointer
advance pointer in longer list to align both lists
else:
for _ in range(lenB - lenA):
currB = currB.next # advance longer list pointer
advance pointer in longer list to align both lists
while currA and currB:
if currA == currB:
return currA # intersection found
currA = currA.next # move forward
currB = currB.next # move forward
move both pointers forward until intersection or end