10min,一次通過(guò)
class Solution(object):
def getIntersectionNode(self, headA:ListNode, headB:ListNode):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
cnt1,cnt2=0,0
cur=headA
while cur:
cnt1+=1
cur=cur.next
cur=headB
while cur:
cnt2+=1
cur=cur.next
while cnt1>cnt2:
headA=headA.next
cnt1-=1
while cnt1<cnt2:
headB=headB.next
cnt2-=1
while headA and headB!=headA: # 沒(méi)有公共節(jié)點(diǎn)
headB=headB.next
headA=headA.next
return headA
考慮到了兩個(gè)都為空,沒(méi)有公共節(jié)點(diǎn)的情況,很好,一次通過(guò)