题目描述:输入两个链表,找出它们的第一个公共结点。
【分析】
上图就是一个有公共结点例子,在公共结点之后,两个链表指针指向的地址相同。
先把长的链表的头砍掉,让两个链表长度相同,这样,同时遍历也能找到公共结点。此时,时间复杂度O(m+n),空间复杂度为O(MAX(m,n))。
/*
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=GetListLen(pHead1);//获取两链表长度
int len2=GetListLen(pHead2);
ListNode *pHeadLong=pHead1;//先默认pHead1长,在根据len长度调整长
ListNode *pHeadShot=pHead2;
int lendif=len1-len2;
if(len1<len2){
ListNode *pHeadLong=pHead2;//根据len长度调整
ListNode *pHeadShot=pHead1;
lendif=len2-len1;
}
/*去掉长链表多余的元素,使得两链表一样长*/
for(int i=0;i<lendif;i++)//去掉多出的lendif长度
{
pHeadLong=pHeadLong->next;
}
while(pHeadShot!=NULL && pHeadShot!=NULL && pHeadShot!=pHeadLong)//遍历链表,找到相等的节点
{
pHeadLong=pHeadLong->next;
pHeadShot=pHeadShot->next;
}
return pHeadLong;//pHeadShot或pHeadLong都可以,二者相等
}
int GetListLen(ListNode* pHead)//获取链表长度函数
{
if(pHead==NULL)
return 0;
int len=1;
while(pHead->next!=NULL)
{
pHead=pHead->next;
len++;
}
return len;
}
};