LeetCode-160. 相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

LeetCode-剑指 Offer 52. 两个链表的第一个公共节点一模一样,这里给出代码,原理可到该篇查看

# 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 not headA or not headB:
            return None
        a, b = headA, headB
        while a != b:
            if a.next == None and b.next == None:
                return None
            a = a.next if a.next else headB
            b = b.next if b.next else headA
        return a


posted @ 2021-07-21 12:27  小Aer  阅读(2)  评论(0编辑  收藏  举报  来源