题目描述

思路:
就是找两个链表相同的一个节点,需要注意的是由于两个链表的长度可能不相等,因此要找到链表长度的差值,让长链表找差值步数到与短链表对齐。为什么要这样呢,因为链表后面都是连着的,在前面就出现相同节点的情况其实是不合理的,因为链表不够长。 所以我们遍历一下找到差值就好了。
时间复杂度:O(n + m)
空间复杂度:O(1)
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
typedef struct ListNode Node;
Node* tempLong;
Node* tempShort;
int lenA=0;
int lenB=0;
int gap=0;
tempLong=headA;
while(tempLong)
{
lenA++;
tempLong=tempLong->next;
}
tempLong=headB;
while(tempLong)
{
lenB++;
tempLong=tempLong->next;
}
if(lenA>lenB)
{
tempLong=headA;
tempShort=headB;
gap=lenA-lenB;
}
else
{
tempLong=headB;
tempShort=headA;
gap=lenB-lenA;
}
while(gap--)
{
tempLong=tempLong->next;
}
while(tempLong&&tempShort)
{
if(tempLong==tempShort)
{
return tempLong;
}
else
{
tempLong=tempLong->next;
tempShort=tempShort->next;
}
}
return NULL;
}