2020.8.18更新
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
int Len1 = getListLength(headA);//计算长度
int Len2 = getListLength(headB);
int dif = Len1 - Len2;
ListNode* pListLong = headA;
ListNode* pListShort = headB;
if (Len1 < Len2) {//len1<len2时,交换
swap(pListLong, pListShort);
dif = Len2 - Len1;
}
for (int i = 0; i < dif; i++) {
pListLong = pListLong->next;
}
while (pListLong != nullptr && pListShort != nullptr && pListLong != pListShort) {//long不为空,short不为空,两者不等
pListLong = pListLong->next;
pListShort = pListShort->next;
}
return pListLong;
}
int getListLength(ListNode* list) {//获取长度
unsigned int nLength = 0;
ListNode* pNode = list;
while (pNode != nullptr) {
nLength++;
pNode = pNode->next;
}
return nLength;
}
};
解题思路
采用两个指针,快指针指向长链表,慢指针指向短链表,先求出两者的长度,再求出长链表比短链表的差值diff,之后让快指针先走diff步后,再和慢指针一起走,直到达到边界条件为止
时间复杂度
o(m+n),m和n分别为两个链表的长度
代码
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* l1 = headA, * l2 = headB;
//求l1的长度
int countL1 = 0;
while (l1 != nullptr)
{
countL1++;
l1 = l1->next;
}
//求l2的长度
int countL2 = 0;
while (l2 != nullptr)
{
countL2++;
l2 = l2->next;
}
//求l1和l2的差值,l1指向长链表,l2指向短链表
l1 = headA;
l2 = headB;
int diff = countL1 - countL2;
//判断两者谁更长
if (countL1 < countL2)
{
l1 = headB;
l2 = headA;
diff = countL2 - countL1;
}
//l1先走diff步
while (diff--)
{
l1 = l1->next;
}
//找共同节点
while (l1 != nullptr && l2 != nullptr && l1 != l2)
{
l1 = l1->next;
l2 = l2->next;
}
return l1;
}
};