题目链接:https://leetcode.cn/problems/intersection-of-two-linked-lists/
难度:简单

描述:
给你两个单链表的头节点 headAheadB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null

题解

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
  8. a, b = headA, headB
  9. while a != b:
  10. a = a.next if a else headB
  11. b = b.next if b else headA
  12. return a