160. 相交链表

实现版本一

# 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):
        ptrA = headA
        ptrB = headB
        numA = 0
        numB  = 0
        while (ptrB):
            numB += 1
            ptrB = ptrB.next

        while (ptrA):
            numA += 1
            ptrA = ptrA.next
            
        # 将两个链表尾对齐,找到初始位置
        posA = numA - min(numA, numB)
        posB = numB - min(numA, numB)

        ptrA = headA
        ptrB = headB
        while (posA):
            ptrA = ptrA.next
            posA -= 1
        while (posB):
            ptrB = ptrB.next
            posB -= 1

        while (ptrA and ptrB):
            if (ptrA == ptrB):
                return ptrA
                break
            ptrA = ptrA.next
            ptrB = ptrB.next

        else:
            return None

遇到的问题

刚开始审错题,误以为两个链表一样长

对于输出是什么没有搞清楚,最初是采取print和返回str,后面看到提示报错才反应过来只需要返回链表节点

要先搞清出报错给的信息,很重要

AttributeError: 'str' object has no attribute 'val'
                                      ^^^^^^^^^^^^^^^^^^^^^
    prefix = "Intersected at '%d'" % (intersection_node.val)
Line 94 in _driver (Solution.py)
    _driver()
Line 114 in <module> (Solution.py)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值