题目描述
输入两个链表,找出它们的第一个公共结点。
解题思路:
设 A 的长度为 a + c,B 的长度为 b + c,其中 c 为尾部公共部分长度,可知 a + c + b = b + c + a。
非常简洁:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//a+C+b=b+C+a;一个走到头再从另一个的头开始走。然后就可以相遇在交点。
ListNode *a=pHead1;
ListNode *b=pHead2;
while(a!=b)
{
a==NULL?a=pHead2:a=a->next;
b==NULL?b=pHead1:b=b->next;
}
return a;
}
};