image.png
- 雙指針?biāo)枷牍藓瑑蓚€指針同時移動畦木,在經(jīng)過a+b+c的長度后會在交點相遇笨觅,應(yīng)該是最優(yōu)解法绞绒。
- 直接判斷兩個node是否相等而非判斷其val相等即可
- 或許也可以構(gòu)建兩個鏈表對應(yīng)的倒序鏈表婶希,然后從頭開始比較即可,時間復(fù)雜度稍微高點蓬衡。
# 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
"""
if headA is None or headB is None:
return None
pA = headA
pB = headB
while pA != pB and (pA or pB):
if pA is None:
pA=headB
else:
pA=pA.next
if pB is None:
pB=headA
else:
pB=pB.next
if pA is None:
return None
else:
return pA
```