题目描述
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
思路
- 首先确定两个链表的长度,然后移动长链表的指针至共同长度处后开始遍历
- 思路类似,不过不需要求链长,目的还是使得两个链表从共同长度处开始遍历
代码
方法1:
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == NULL || pHead2 == NULL)
return NULL;
ListNode* List1 = pHead1;
ListNode* List2 = pHead2;
int List1_Length = 0;
int List2_Length = 0;
int count = 0;
while(List1 != NULL)
{
List1 = List1->next;
List1_Length++;
}
while(List2 != NULL)
{
List2 = List2->next;
List2_Length++;
}
if (List1_Length > List2_Length)
{
while (count < List1_Length - List2_Length)
{
pHead1 = pHead1->next;
count++;
}
}
else if (List1_Length < List2_Length)
{
while (count < List2_Length - List1_Length)
{
pHead2 = pHead2->next;
count++;
}
}
while (pHead1 != pHead2 && pHead1 != NULL && pHead2 !=NULL)
{
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return pHead1;
}
};
方法2:
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == NULL || pHead2 == NULL)
return NULL;
ListNode* List1 = pHead1;
ListNode* List2 = pHead2;
while (List1 != List2)
{
if (List1 == NULL)
List1 = pHead2;
else
List1 = List1->next;
if (List2 == NULL)
List2 = pHead1;
else
List2 = List2->next;
}
return List1;
}
};