class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
if not headA or not headB:return None
a,b=headA,headB
ans = None
while a or b:
if not a: a=headB
if not b: b=headA
if a==b and not ans: ans=a
a , b = a.next,b.next
return ans
My concise python solution, run in O(n) time and O(1) memory


The variable
ans
is optional right?class Solution: # @param two ListNodes # @return the intersected ListNode def getIntersectionNode(self, headA, headB): if not headA or not headB:return None a,b=headA,headB ans = None while a or b: if not a: a=headB if not b: b=headA if a is b: return a# and not ans: ans=a a , b = a.next,b.next #return ans