Leetcode 160. Intersection of Two Linked Lists

Description: Write a program to find the node at which the intersection of two singly linked lists begins.

Link: https://leetcode.com/problems/intersection-of-two-linked-lists/

Examples:

listA = [4,1,8,4,5], listB = [5,6,1,8,4,5]
intersectVal = 8
listA = [1,9,1,2,4], listB = [3,2,4]
intersectVal = 2

思路: 找到两个单链表交汇的点。交汇点的特征就是,从这个节点以后,所有的节点都相同。所以不妨最简单地分别存headA and headB所有的节点到两个list中,从两个list的结尾开始比较,直到第一个不同的node, 这样后面一个就是交汇点。

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if (not headA) or (not headB): return None
        A = list()
        B = list()
        a = headA
        b = headB
        while a:
            A.append(a)
            a = a.next
        while b:
            B.append(b)
            b = b.next
        n = min(len(A), len(B))
        i = 1
        while i <= n:
            if A[-i] != B[-i]:
                break
            i += 1
        if i > 1:
            return A[-i+1]
        else:
            return None

日期: 2020-12-01  不知不觉就十二月了,时间在跑

 

posted @ 2020-12-01 14:59  summer_mimi  阅读(40)  评论(0编辑  收藏  举报