# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
# check length of list A
lengthA = 0
curA = headA
while(curA):
curA = curA.next
lengthA += 1
# check length of list B
lengthB = 0
curB = headB
while(curB):
curB = curB.next
lengthB += 1
# move longer list's head (longLength - shortLength) steps forward
if lengthB > lengthA:
curB = headB
for i in range(lengthB - lengthA):
curB = curB.next
curA = headA
elif lengthA > lengthB:
curA = headA
for i in range(lengthA - lengthB):
curA = curA.next
curB = headB
else:
curA = headA
curB = headB
# move long / short list head together until there is an meet point
while(curA != curB):
curA = curA.next
curB = curB.next
# each reach its end or meet the intersection point
if curB is None:
return None
else:
return curB
Another interesting way to do it in O(n) time is to
Start from either headA or headB;
Reach the end of the A/B list;
Redirect end of A/B list to B/A start;
If there is intersection, a cycle linked list is promised; if there is no intersection, no cycle in the new list
Then entry point of cycle is the intersection point