/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode * p = pHead1;
int num1 = 0;
int num2 = 0;
while (p)
{
num1++;
p = p->next;
}
ListNode *p2 = pHead2;
while(p2)
{
num2++;
p2 = p2->next;
}
if (num2>num1)
{
int x = num2-num1;
for ( int i = 0 ; i!=x ; i++)
{
pHead2=pHead2->next;
}
while (pHead2)
{
if (pHead2->val == pHead1->val)
return pHead2;
pHead2 = pHead2->next;
pHead1 = pHead1->next;
}
}else{
int x = num1 - num2;
for (int i = 0; i!= x;i++)
{
pHead1 = pHead1->next;
}
while (pHead1)
{
if (pHead1->val == pHead2->val)
return pHead1;
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
}
return NULL;
}
};
輸入兩個鏈表,找出它們的第一個公共結點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.