160. Intersection of Two Linked Lists
Given the heads of two singly linked-lists
headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.Note: Has an easy solution, but O(N) good solution is Medium.
a + c + b = b + c + a
def getIntersectionNode(headA: ListNode, headB: ListNode):
pA = headA
pB = headB
while pA != pB:
pA = headB if pA is None else pA.next
pB = headA if pB is None else pB.next
return pA
# Note: In the case lists do not intersect, the pointers for A and B
# will still line up in the 2nd iteration, just that here won't be
# a common node down the list and both will reach their respective ends
# at the same time. So pA will be NULL in that case
Comments
Post a Comment