160. 相交链表 - 力扣(LeetCode)
题目:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
思路:
求出A、B两个链表的表长len1、len2,分别用两个指针pa、pb,指向两个链表的头结点、让长的那个链表先走|len1-len2|给元素,然后再同时走,两个指针相等的时候就是相交的结点。
代码:
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
int lenA = 0;
int lenB = 0;
struct ListNode* pa = headA;
struct ListNode* pb = headB;
while(pa)
{
lenA++;
pa=pa->next;
}
while(pb)
{
lenB++;
pb=pb->next;
}
pa = headA;
pb = headB;
int difference = 0;//差值
if(lenA > lenB)
{
difference = lenA - lenB;
while(difference--)
{
pa = pa->next;
}
while(pa!=pb && NULL != pa && NULL != pb)
{
pa = pa->next;
pb = pb->next;
}
return pa;
}
else
{
difference = lenB - lenA;
while(difference--)
{
pb = pb->next;
}
while(pa!=pb && NULL != pa && NULL != pb)
{
pa = pa->next;
pb = pb->next;
}
return pa;
}
}



