题解:
# 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) -> Optional[ListNode]:
la=self.length(headA)#引用类内的方法
lb=self.length(headB)
p=headA
q=headB
if la>lb:
for i in range(la-lb):
p=p.next
else:
for i in range(lb-la):
q=q.next
while q!=p and q!=None:#注意python中的空值为None,不为null
q=q.next
p=p.next
if q==p:
return q
else:
return null
def length(self,head):#因为这个方法在类内,所以加self
p=head
num=0
while p!=None:
num=num+1
p=p.next
return num