leedcode 相交鏈表

首先要找兩個鏈表的相交節點,那就要保證從相交節點開始其元素個數相同,否則肯定不是相交節點。所以先通過遍歷長鏈表使其剩餘元素與短鏈表相等。然後同時遍歷兩個鏈表,找到兩個節點相等的位置,該節點即爲相交節點,這裏要注意我們應該比較兩個節點而不是兩個節點的值,因爲我們要保證其值不僅相同還要讓其指向的next相同,其next相同說明其指向了同一個節點,那這個又保證了其後繼節點的後繼又是同一個節點,以此類推,後面的節點都是指向了同一個節點。

# 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
        """
        m = 0
        n = 0
        pNodea = headA
        pNodeb = headB
        if headA is None or headB is None:
            return None
        while(pNodea):
            m += 1
            pNodea = pNodea.next
        while pNodeb:
            n += 1
            pNodeb = pNodeb.next
        pNodea = headA
        pNodeb = headB
        if m > n:
            count = m - n
            while count > 0:
                pNodea = pNodea.next
                count = count - 1
        elif m < n:
            count = n - m
            while count > 0:
                pNodeb = pNodeb.next
                count = count - 1
        while pNodea:
            if pNodea == pNodeb:
                return pNodea
            else:
                pNodea = pNodea.next
                pNodeb = pNodeb.next
        return pNodea

 

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