[leetcode]python3 算法攻略-相交链表

编写一个程序,找到两个单链表相交的起始节点。

方案一:

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA == None or headB == None:
            return
        
        a, b = headA, headB
        la, lb = 1, 1  # 分别记录A,B的长度
        while a.next:
            la += 1
            a = a.next
        while b.next:
            lb += 1
            b = b.next
        if a != b:  # 如果尾节点不相等,那么一定不相交
            return
        
        a, b = headA, headB  # 回到头节点
        if lb > la:  # 将长链表 右移 长度差 
            for _ in range(lb - la):
                b = b.next
        else:
            for _ in range(la - lb):
                a = a.next
        while a:  # 重新遍历,一定能发现相等的节点
            if a == b:
                return a
            a = a.next
            b = b.next

猜你喜欢

转载自blog.csdn.net/zhenghaitian/article/details/81295870