实现版本一
# 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)