leetcode 相交链表 python3

在这里插入图片描述
在这里插入图片描述

方案一:将两个链表分别转换为两个列表,从列表的尾部开始对比两个列表的节点是否相等,并进行相应操作
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None
        wei_A = []
        while headA:
            wei_A.append(headA)
            headA=headA.next
        wei_A = wei_A[::-1]
        wei_B = []
        while headB:
            wei_B.append(headB)
            headB = headB.next
        wei_B = wei_B[::-1]
        count = -1
        lA = len(wei_A)
        lB = len(wei_B)
        if lA < lB:
            copy = wei_B
            wei_B = wei_A
            wei_A = copy
            lA,lB=lB,lA
        for i in range(lB):
            if wei_A[i] == wei_B[i]:
                count+=1
            else:
                break
        if count != -1:
            return wei_A[count]
        else:
            return None
#一种比较巧妙的方式是,分别为链表A和链表B设置指针A和指针B,然后开始遍历链表,如果遍历完当前链表,则将指针指向另外一个链表的头部继续遍历,直至两个指针相遇。
#最终两个指针分别走过的路径为:
#指针A :a+c+b
#指针B :b+c+a
#明显 a+c+b = b+c+a,因而如果两个链表相交,则指针A和指针B必定在相交结点相遇。


class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        if not headA or not headB:
            return None
        nodeA = headA
        nodeB = headB
        while(nodeA !=nodeB):
            nodeA = nodeA.next if nodeA else headB
            nodeB = nodeB.next if nodeB else headA
        return nodeA
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        seen = set()
        p = headA
        while p:
            seen.add(p)
            p = p.next

        p = headB
        while p:
            if p in seen:
                return p
            p = p.next

        return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值