劍指offer 兩個鏈表的第一個公共結點

題目描述

輸入兩個鏈表,找出它們的第一個公共結點。

Solution

雙指針。

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        if pHead1 is None or pHead2 is None:
            return None
        h1, h2 = pHead1, pHead2
        cnt1, cnt2 = 0, 0
        while h1 is not None:
            cnt1 += 1
            h1 = h1.next
        while h2 is not None:
            cnt2 += 1
            h2 = h2.next
        h1, h2 = pHead1, pHead2
        if cnt1 < cnt2:
            h1, h2 = pHead2, pHead1,
        step = abs(cnt1-cnt2)
        for _ in range(step):
            h1 = h1.next
        while h1 is not None:
            if h1 is h2:
                return h1
            h1 = h1.next
            h2 = h2.next
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章