被秀到了
判断两链表是否有交点,有则输出交点,无则输出 null
这道题解法很多,最简洁的解法为:
# 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:
h1, h2 = headA, headB
while h1 != h2:
h1 = h1.next if h1 else headB
h2 = h2.next if h2 else headA
return h1
1.有交点:
两个指针走完自己的路径后再走对方的路径,总长度一样,因此必定相遇
2.无交点
两个指针走完自己的路径后再走对方的路径,同时走到 null,跳出循环