题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给两个链表头,判断这两个链表是否相交。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
# 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) -> Optional[ListNode]:
p, q = headA, headB
while not p == q:
p = p.next if p else headB
q = q.next if q else headA
return p