160. 相交链表
注:两个链表相交不是指两个节点的值相等,而是指节点所在的地址
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution:def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:curA = headAcurB = headBlenA = 0lenB = 0# 求出两个链表的长度while curA:lenA += 1curA = curA.nextwhile curB:lenB += 1curB = curB.next# 这个地方是因为上面求长度的时候已经遍历到curA和curB的末尾了curA = headAcurB = headBif lenA > lenB:lenA, lenB = lenB, lenAcurA, curB = curB, curA# 使curA和curB在同一起点上for _ in range(lenB - lenA):curB = curB.nextwhile curA:if curA == curB:return curAelse:curA = curA.nextcurB = curB.nextreturn None