【面試題41】兩個鏈表的第一個公共結(jié)點

題目描述:
輸入兩個鏈表,找出它們的第一個公共結(jié)點。
【思路】
兩個鏈表成Y字形,故只需將長的鏈表先走多余的長度,再兩個鏈表同時走,求出相應(yīng)的公共節(jié)點即可
【代碼】

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        def list_len(node):
            l = 0
            while node!=None:
                l+=1
                node = node.next
            return l
        p1_len = list_len(pHead1)
        p2_len = list_len(pHead2)
        if p1_len > p2_len:
            pLong = pHead1
            pShort = pHead2
            gap_len = p1_len-p2_len
        else:
            pLong = pHead2
            pShort = pHead1
            gap_len = p2_len-p1_len
        #讓長鏈表先走
        for i in range(gap_len):
            pLong=pLong.next
        #尋找最先的公共節(jié)點
        while pLong!=None and pShort!=None:
            if pLong==pShort:
                return pLong
            else:
                pLong = pLong.next
                pShort = pShort.next
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容