题目链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/
题目描述:
输入两个链表,找出它们的第一个公共节点。
如下面的两个链表:
在节点 c1 开始相交。
示例 1:
示例 2:
题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *PA = headA;
ListNode *PB = headB;
int l1 = 0;
int l2 = 0;
while(PA != NULL)
{
l1++;
PA = PA->next;
}
while(PB != NULL)
{
l2++;
PB = PB->next;
}
PA = headA;
PB = headB;
if(l1 > l2)
{
int s = l1 - l2;
while(s--)
{
PA = PA ->next;
}
}else if(l1 < l2)
{
int s = l2 - l1;
while(s--)
{
PB = PB ->next;
}
}
while(PA != NULL)
{
if(PA == PB)
return PA;
PA = PA -> next;
PB = PB -> next;
}
return NULL;
}
};