1. 程式人生 > >leetcode 相交連結串列 python實現

leetcode 相交連結串列 python實現

1 class Solution(object): 2 def getIntersectionNode(self, headA, headB): 3 """ 4 :type head1, head1: ListNode 5 :rtype: ListNode 6 """ 7 # 如果有一個連結串列是空的 那就沒有交叉 8 if headA is None or headB is None: 9 return None 10 # 計算一下兩個連結串列的長度
11 ca = headA 12 cb = headB 13 ta, tb = 1, 1 14 while ca.next is not None: 15 ta += 1 16 ca = ca.next 17 while cb.next is not None: 18 tb += 1 19 cb = cb.next 20 # 如果最後一個元素都不一樣說明沒有交叉 21 if ca.val != cb.val:
22 return None 23 # 如果兩個連結串列長度不一樣,將長得連結串列指標後移 24 ca = headA 25 cb = headB 26 while tb > ta: 27 tb -= 1 28 cb = cb.next 29 while ta > tb: 30 ta -= 1 31 ca = ca.next 32 # 從倒數長度相同的 短的連結串列的開頭開始一位一位比較
33 while ca is not None and cb is not None: 34 if ca.val == cb.val: 35 return ca 36 ca = ca.next 37 cb = cb.next