一般的想法是用栈,可是超出内存了。
先把两个长的那部分截掉,然后再一一比较。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
int GetLength(ListNode* pHead1)
{
if (pHead1 == NULL)
return 0;
int count = 1;
while (pHead1->next)
{
count++;
pHead1 = pHead1->next;
}
return count;
}
ListNode* ResetStarNode(ListNode* pHead1,int dif)
{
while (dif--)
pHead1 = pHead1->next;
return pHead1;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2)
{
int len1 = GetLength(pHead1);
int len2 = GetLength(pHead2);
int dif = abs(len1 - len2);
if (len1>len2)
{
pHead1 = ResetStarNode(pHead1,dif);
}
else
pHead2 = ResetStarNode(pHead2,dif);
while (pHead2 != NULL&&pHead1 != NULL)
{
if (pHead1 ==pHead2) return pHead1;
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return NULL;
}
};