劍指Offer(Python多種思路實現):兩個鏈表的第一個公共節點

劍指Offer(Python多種思路實現):兩個鏈表的第一個公共節點

面試52題:

題目:兩個鏈表的第一個公共節點

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

解題思路一:

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        length1=self.GetLength(pHead1)
        length2=self.GetLength(pHead2)
        
        if length1>length2:
            headLong=pHead1
            headShort=pHead2
        else:
            headLong=pHead2
            headShort=pHead1
        diff=abs(length1-length2)
        
        for i in range(diff):
            headLong=headLong.next
        
        while headLong!=None and headShort!=None and headLong!=headShort:
            headLong=headLong.next
            headShort=headShort.next
        return headLong
           

    
    def GetLength(self,pHead):
        length=0
        while pHead:
            pHead=pHead.next
            length += 1
        return length

解題思路二:

def getIntersectionNode(self, headA, headB):
    p1, p2 = headA, headB
    while p1 is not p2:
        p1 = p1.next if p1 else headB
        p2 = p2.next if p2 else headA
    return p1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章