题目链接:
https://www.acwing.com/activity/content/problem/content/4299/
/**
* 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 pa = headA, pb = headB;
while(pa != pb){//循环终止条件,两个指针指向同一个节点时终止
if(pa) pa = pa->next;//如果当前节点存在,继续向后遍历
else pa = headB;//否则,从另一个链表的头开始遍历
if(pb) pb = pb->next;
else pb = headA;
}
//退出循环时,pa和pb指向第一个公共节点,或者都为NULL,两个链表不存在相同的节点
return pa;
}
};