题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
思路
第一次遍历两个链表得到两个链表的长度,以及两个链表长度的差值error;第二次遍历两个链表时,先在较长的链表上走error步,接着分别遍历两个链表,找到的第一个相同的节点即为第一个公共节点,时间复杂度为O(m+n)。比如在下图的两个链表中,第一次遍历两个链表得到两个链表的长度为5和4,以及两个链表的差error=1;第二次遍历两个链表时,先再较长链表上走error部,即先走一步,然后分别从结点2和结点4出发同时遍历两个结点,直到找到他们的第一个公共结点6。
C++
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
// 计算链表长度
int len1 = Lenth(pHead1);
int len2 = Lenth(pHead2);
//两个链表长度的差值
if (len1 > len2)
pHead1 = firstnode(pHead1, len1 - len2);
else
pHead2 = firstnode(pHead2, len2 - len1);
while (pHead1 != NULL)
{
if (pHead1 == pHead2)
return pHead1;
pHead1 = pHead1 -> next;
pHead2 = pHead2 -> next;
}
return NULL;
}
int Lenth(ListNode *p)
{
int count = 0;
while (p != NULL)
{
count++;
p = p -> next;
}
return count;
}
ListNode *firstnode(ListNode *p, int len)
{
int temp = 0;
while (temp < len)
{
p = p -> next;
temp++;
}
return p;
}
};
参考
https://www.cnblogs.com/wanglei5205/p/8893714.html