题目要求
编写一个程序,找到两个单链表相交的起始节点。
思路
先计算两个链表的长度,如果两个链表结束的结点不一样,肯定不是相交链表,如果结束结点一样,那肯定相交,计算两个链表长度的差值,让长的先走差值步,然后两个链表同时向下走,进行比较,第一个相等的结点就是两个链表相交的起始结点。
图解
代码实现
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
int lenA = 0, lenB = 0;
struct ListNode* curA = headA;
struct ListNode* curB = headB;
while (curA)
{
curA = curA->next;
lenA++;
}
while (curB)
{
curB = curB->next;
lenB++;
}
if (curA != curB)
{
return NULL;
}
int n = abs(lenA - lenB);
curA = headA;
curB = headB;
while (n--)
{
if (lenA > lenB)
{
curA = curA->next;
}
if (lenA < lenB)
{
curB = curB->next;
}
}
while (curA != curB)
{
curA = curA->next;
curB = curB->next;
}
return curA;
}