# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution1(object):
"""
two pass method
in first pass get each list's length la,lb, we assume that la > lb
the longer link list take la - lb steps first , the they set out at the same time and will meet at the same time(if have)
"""
def getIntersectionNode(self,headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
countA,countB,pNodeA,pNodeB = 0,0,headA,headB
while(pNodeA):
countA += 1
pNodeA = pNodeA.next
while(pNodeB):
countB += 1
pNodeB = pNodeB.next
if countA < countB:
headA, headB = headB, headA
countA, countB = countB, countA
while(countA != countB):
countA -=1
headA = headA.next
while(headA and headB and headA!=headB):
headA = headA.next
headB = headB.next
return headA
class Solution2(object):
"""
Solution1 without count but pointer
"""
def getIntersectionNode(self,headA, headB):
l1,l2 = headA, headB
while(l1 and l2):
l1,l2 = l1.next, l2.next
if l1 is None:
l1,l2 = l2,l1
headA,headB = headB, headA
while(l1):
headA = headA.next
l1 = l1.next
while(headA and headB and headA != headB):
headA = headA.next
headB = headB.next
return headA if headA is None else headA.val
class Solution3(object):
"""
If there exits an intersection between headA and headB ,
If two people start from headA and headB and change to the other list if they arrive in then end,
they will meet at the intersection node (because they had walk the same distance)
if the don't have intersection , after walk through two linklist, they have experience the same distance and come be none(None == None)
"""
def getIntersectionNode(self,headA, headB):
l1,l2 = headA, headB
while(l1 != l2 ):
l1 = l1.next if l1 != None else headB
l2 = l2.next if l2 != None else headA
return l1