题目描述
输入两个链表,找出它们的第一个公共结点。
思路:
首先判断链表是否有公共节点,分别遍历两个链表到最后一个节点,如果最后一个节点相等,说明有公共节点。
在上一步遍历时保存下两个链表的长度,dis保存两个链表的长度差,然后让fast指针指向较长的链表,slow指向较短的链表,fast先走dis步,然后fast和slow一起往后走,第一次相遇的位置就是第一个公共节点。
在线测试
AC代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==NULL||pHead2==NULL)
return NULL;
int len1=1;
int len2=1;
ListNode* pNode1=pHead1;
while(pNode1->next)
{
len1++;
pNode1=pNode1->next;
}
ListNode* pNode2=pHead2;
while(pNode2->next)
{
len2++;
pNode2=pNode2->next;
}
if(pNode1!=pNode2)
return NULL;
int dis=0;
ListNode* fast;
ListNode* slow;
if(len1>len2)
{
dis=len1-len2;
slow=pHead2;
fast=pHead1;
}
else
{
dis=len2-len1;
slow=pHead1;
fast=pHead2;
}
int i=0;
while(i<dis)
{
fast=fast->next;
i++;
}
while(slow!=fast)
{
slow=slow->next;
fast=fast->next;
}
return slow;
}
};