目录
![](https://img2020.cnblogs.com/blog/1517575/202101/1517575-20210116092343663-499331697.png)
思路分析
这个题目只有两种情况,如下图
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *findFirstCommonNode(ListNode *headA, ListNode *headB) {
auto p=headA,q=headB;
while(p!=q){
p= p ? p->next : headB;
q= q ? q->next : headA;
}
return q;
}
};
python
# 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:
p = headA
q = headB
while p!=q: # 最后一定会相等
p = p.next if p else headB
q = q.next if q else headA
return q