问题:
# 给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
方法:双指针法分别遍历两个链表,第一次相遇即为相交点
参考代码:
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return pta, ptb = headA, headB while pta != ptb: if not pta: pta = headB else: pta = pta.next if not ptb: ptb = headA else: ptb = ptb.next return pta