AcWing 66. 两个链表的第一个公共结点
原题链接
简单
C++ 代码
/**
* 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) {
if(!headA || !headB) return nullptr;
// 求出两个链表的长度
auto curA = headA, curB = headB;
int lengthA = 0, lengthB = 0;
while(curA) {curA = curA->next; lengthA++;}
while(curB) {curB = curB->next; lengthB++;}
// 较长链表先走差值步
int n = abs(lengthA - lengthB);
if(lengthA > lengthB)
while(n--) headA = headA->next;
else
while(n--) headB = headB->next;
// 两个链表一起走
while(headA != headB)
{
headA = headA->next;
headB = headB->next;
}
return headA;
}
};