# 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) -> ListNode:
if headA is None or headB is None:
return None
pa, pb = headA, headB
while pa is not pb:
if pa is not None:
pa = pa.next
else:
pa = headB
if pb is not None:
pb = pb.next
else:
pb = headA
return pa
为什么不相交出现没有死循环:
如果不相交说明两个指针走过的次数都为m+n,他们会同时到达链尾,也就是它们同时会指向NULL,达到跳出循环的条件
第一种方法: 语言特性 hashmap