力扣刷题(python)50天——第三十七天:相交链表

力扣刷题(python)50天——第三十七天:相交链表

题目描述

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

方法

将两个链表的节点分别按原来顺序放到两个列表中,从最后一位开始逐个检测是否有相同节点。

解答

# 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
        """
        list1=[]
        list2=[] 
        while headA:
            list1+=[headA]
            headA=headA.next
        while headB:
            list2+=[headB]
            headB=headB.next
        if not list1:
            return None
        if not list2:
            return None
        
        if list1[-1]!=list2[-1]:
            return None
        while list1 and list2:
            if list1[-1]==list2[-1]:
                f1=list1.pop(-1)
                list2.pop(-1)
            else:
                return f1
        return f1

执行结果

力扣刷题(python)50天——第三十七天:相交链表_第1张图片

提升:

双指针与哈希表

https://leetcode-cn.com/problems/intersection-of-two-linked-lists/solution/xiang-jiao-lian-biao-by-leetcode/

其实我最初的想法也是哈希表或列表来直接存储地址,但由于即使找到地址,python也难以将地址中的数据返回

你可能感兴趣的:(leetcode刷题,相加链表,链表,python,力扣,leetcode)