160. Intersection of Two Linked Lists

嗯 第一种想到的办法是stack,从后向前找到第一个相等的位置:

# 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
        """
        if not headA or not headB:
            return None
        if not headA.next and not headB.next:
            if headA == headB:
                return headA
            else:
                return None
        stack1 = []
        stack2 = []
        while headA:
            stack1.append(headA)
            headA = headA.next
        while headB:
            stack2.append(headB)
            headB = headB.next
        i = len(stack1) - 1
        j = len(stack2) - 1
        while i >= 0 and j >= 0:
            if i-1 >= 0 and j-1 >= 0 and stack1[i-1] != stack2[j-1] and stack1[i] == stack2[j]:
                return stack1[i]
            elif stack1[i] == stack2[j] and (i == 0 or j == 0):
                return stack1[i]
            else:
                i -= 1
                j -= 1
        return None
        
        

第二种办法是从前向后,先遍历出两个链表的长度,然后把差长先去除,再同时遍历找到相等的位置

# 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
        """
        if not headA or not headB:
            return None
        if not headA.next and not headB.next:
            if headA == headB:
                return headA
            else:
                return None
        counta, countb = 0, 0
        a, b = headA, headB
        while a:
            counta += 1
            a = a.next
        while b:
            countb += 1
            b = b.next
        a, b = headA, headB
        if counta > countb:
            m = counta - countb
            while m :
                a = a.next
                m -= 1
            while a and b:
                if a == b:
                    return a
                a = a.next
                b = b.next
            return None
        else:
            m = countb - counta
            while m:
                b = b.next
                m -= 1
            while a and b:
                if a == b:
                    return a
                a = a.next
                b = b.next
            return None

你可能感兴趣的:(160. Intersection of Two Linked Lists)