方法一:双指针
1.1:自己写的
时间复杂度:O(n+m)
空间复杂度:O(1)
class Solution
{
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
{
int lenA = 0;
int lenB = 0;
ListNode* pA = headA;
ListNode* pB = headB;
while (pA != nullptr)
{
lenA++;
pA = pA->next;
}
while (pB != nullptr)
{
lenB++;
pB = pB->next;
}
if (lenA > lenB)
{
int dif = lenA - lenB;
pA = headA;
pB = headB;
for (int i = 0; i < dif; i++)
{
pA = pA->next;
}
while (pA != nullptr || pB != nullptr)
{
if (pA == pB)
{
return pA;
}
pA = pA->next;
pB = pB->next;
}
return nullptr;
}
int dif = lenB - lenA;
pA = headA;
pB = headB;
for (int i = 0; i < dif; i++)
{
pB = pB->next;
}
while (pA != nullptr || pB != nullptr)
{
if (pA == pB)
{
return pB;
}
pA = pA->next;
pB = pB->next;
}
return nullptr;
}
};
1.2 官方解法
时间复杂度:O(n+m)
空间复杂度:O(1)
class Solution
{
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB)
{
ListNode* pA = headA;
ListNode* pB = headB;
while (pA != pB)
{
pA = (pA != nullptr) ? pA->next : headB;
pB = (pB != nullptr) ? pB->next : headA;
}
return pA;
}
};