提示:
- 使用數學方法先記錄兩個鏈表的長度LA,LB,求差,將長的鏈表移動abs(LA-LB),後同時移動,相等即爲交點。時將複雜度爲O(N);
代碼:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int countA = 0;
int countB = 0;
ListNode *ptrA = headA;
ListNode *ptrB = headB;
while(ptrA)
{
countA ++;
ptrA = ptrA->next;
}
while(ptrB)
{
countB++;
ptrB = ptrB->next;
}
ptrA = headA;
ptrB = headB;
if(countA > countB)
{
int dalta = countA - countB;
while(ptrA && dalta--)
{
ptrA = ptrA->next;
}
}
else
{
int dalta = countB - countA;
while(ptrB && dalta--)
{
ptrB = ptrB->next;
}
}
while(ptrA && ptrB)
{
if(ptrA == ptrB)
{
return ptrA;
}
ptrA = ptrA->next;
ptrB = ptrB->next;
}
return NULL;
}
};