题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式
显示的,保证传入数据是正确的)
考察点:时间空间复杂度分析;链表编程。
思路:一开始想到的是遍历其中一条链表,找到一个节点,就去另一条链表中去找相同的,这样的复杂度比较高。
所以借用前文的思路,既然是找共同节点,那么两条链表就是Y型。那么让长链条先走差值的步数,
之后两条链一块走,直到走到共同节点。
struct ListNode {
int val;
struct ListNode* next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
int getListLength(ListNode* pHead)//获取链表长度
{
int count = 0;
while (pHead != NULL)
{
pHead = pHead->next;
count++;
}
return count;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL || pHead2 == NULL)
return NULL;
int len1 = getListLength(pHead1);
int len2 = getListLength(pHead2);
int len;
ListNode* pLongList;
ListNode* pShortList;//声明变量
if (len1 >= len2)//两种情况分别初始化
{
len = len1 - len2;
pLongList = pHead1;
pShortList = pHead2;
}
else
{
len = len2 - len1;
pLongList = pHead2;
pShortList = pHead1;
}
for (int i = 0; i < len; i++)//让长链先走个差值的步数
{
pLongList = pLongList->next;
}
while (pLongList != NULL&&pShortList!=NULL)//不为空就同步走
{
if (pLongList == pShortList)//找到共同节点就返回
{
return pLongList;
}
else//没找到就接着走
{
pLongList = pLongList->next;
pShortList = pShortList->next;
}
}
return NULL;
}
};