相交链表(力扣160 easy)
160. 相交链表
算法思路
-  核心思想: - 使用两个指针 pA和pB,分别从headA和headB开始遍历。
- 当 pA遍历到链表 A 的末尾时,跳转到链表 B 的头节点;当pB遍历到链表 B 的末尾时,跳转到链表 A 的头节点。
- 如果两个链表相交,pA和pB最终会在相交节点相遇;如果不相交,pA和pB会同时到达None。
 
- 使用两个指针 
-  具体步骤: - 初始化 pA = headA,pB = headB。
- 当 pA != pB时:- 如果 pA为空,跳转到headB;否则继续遍历pA.next。
- 如果 pB为空,跳转到headA;否则继续遍历pB.next。
 
- 如果 
- 返回 pA(即相交节点)。
 
- 初始化 
-  关键点: - 通过跳转指针的方式,确保两个指针遍历的总长度相同。
- 时间复杂度为 O(m + n),空间复杂度为O(1)。
 
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def getIntersectionNode(self, headA, headB):if not headA or not headB:return NonepA, pB = headA, headBwhile pA != pB:pA = headB if not pA else pA.nextpB = headA if not pB else pB.nextreturn pA
题解里看到的图解,很清晰
