描述
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
图示两个链表在节点 c1 开始相交:
示例
示例1
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
输出:Intersected at ‘8’
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,6,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
— 请注意相交节点的值不为 1,因为在链表 A 和链表 B 之中值为 1 的节点 (A 中第二个节点和 B 中第三个节点) 是不同的节点。换句话说,它们在内存中指向两个不同的位置,而链表 A 和链表 B 中值为 8 的节点 (A 中第三个节点,B 中第四个节点) 在内存中指向相同的位置。
示例2
输入:intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Intersected at ‘2’
解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [1,9,1,2,4],链表 B 为 [3,2,4]。
在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
示例3
输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。
由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
这两个链表不相交,因此返回 null 。
解题思路以及代码
计算两个链表的结点数,结点个数多的链表先走两个链表长度之差,注意如果链表相交则最后一个链表位置是一样的,如果不相交则最后一个链表位置是不一样的,如果相交,然后在两个链表指针在一起走。千万不能用val值判断!
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
struct ListNode*curA=headA,*curB=headB;
//A结点数
int countA=1;
while(curA->next != NULL)
{
++countA;
curA=curA->next;
}
//B结点数
int countB=1;
while(curB->next != NULL)
{
++countB;
curB=curB->next;
}
//判断不相交
if(curA != curB)
{
return NULL;
}
//相交
//结点多的先走K步
struct ListNode*longlist=headA,*shortlist=headB;
if(countA < countB)
{
longlist=headB;
shortlist=headA;
}
int k=abs(countA-countB);
while(k--)
{
longlist=longlist->next;
}
//在一起走
while(longlist != shortlist)
{
longlist=longlist->next;
shortlist=shortlist->next;
}
return longlist;
}