力扣刷题(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

执行结果

在这里插入图片描述

提升:

双指针与哈希表

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值