相交链表

class Solution:
    def getIntersectionNode(self, headA, headB):
        if headA is None or headB is None:
            return None
        lenA = self.getLength(headA)
        lenB = self.getLength(headB)
        print("lenA is {}, lenB is {}".format(lenA, lenB))
        it = ListNode(0)

        if lenA > lenB:
            it = self.movePointer(headA, lenA - lenB)
            itb = headB
            print("it.val is {}".format(it.val))

            while it:
                if it.val != itb.val:
                    it = it.next
                    itb = itb.next
                else:
                    return it

            if it is None:
                return None
        else:
            it = self.movePointer(headB, lenB - lenA)
            ita = headA
            while it:
                if it.val != ita.val:
                    it = it.next
                    ita = ita.next
                else:
                    return it
            if it is None:
                return None


    def movePointer(self, head, count):
        it = head
        while count > 0:

            if it:
                it = it.next
            count -= 1
        return it



    def getLength(self, head):
        count = 1
        it = head
        if head is None:
            return 0
        while it:
            count += 1
            it = it.next
        return count

猜你喜欢

转载自blog.csdn.net/weixin_36149892/article/details/80385145