思路:兩個鏈表第一個公共結點之後的結點都相同,較長的結點先走,走到兩個鏈表相同長度時,
同時走,當兩鏈表結點相同時,即爲公共結點
另一種思路:鏈表尾部相同,從尾部走,最後一個相同的結點,即爲所求結點
所以就要用到棧了。
上代碼:
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
int length1 = GetLength(pHead1);
int length2 = GetLength(pHead2);
int res = length1-length2;
if(res < 0)
res = length2-length1;
ListNode *plong = length1>length2?pHead1:pHead2;
ListNode *pshort = length1>length2?pHead2:pHead1;
for(int i=0;i<res;++i)
plong = plong->next;
while(plong != NULL && pshort != NULL && plong != pshort)
{
plong = plong->next;
pshort = pshort->next;
}
ListNode *pFirstCommon = plong;
return pFirstCommon;
}
//計算鏈表長度
int GetLength(ListNode *pHead)
{
ListNode *p = pHead;
int length = 0;
while(p != NULL)
{
length++;
p = p->next;
}
return length;
}
};