原题传送门
示例 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 。
提示:
看完了上面这些题目的描述,相信很多同学都被此题吓住了,觉得这个题目很难,自己做不出来,但是进到原题中可以看到这是一道力扣上的简单题,正确率也不低,有65%左右,所以不要害怕,我带你来慢慢分析一下,如何去求解本题⌛️
好,看完题目的描述,我们来分析一下去求解这道题目,
ListNode* curA = headA, *curB = headB; //遍历
int lenA = 0, lenB = 0; //记录两个链表的长度
while(curA->next){lenA++;curA = curA->next;
}while(curB->next){lenB++;curB = curB->next;
}if(curA != curB)return NULL; //若两个结点的地址不同,则表示不相交,return NULL
ListNode* longer = headA, *shorter = headB; //先假设链表A长于链表B
if(lenB > lenA){ //若是假设错误则交换longer = headB;shorter = headA;
}
int gap = abs(lenA - lenB); //求出两个链表的长度差
while(gap--)longer = longer->next; //先让长的链表走gap步,使得两链表位于同一起跑线
while(longer != shorter) //一同往后走,寻找两链表的交点(此时一定相交)
{longer = longer->next;shorter = shorter->next;
}
return longer;
展示一下整体的代码,不过还是自己去敲一遍比较好哦
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {ListNode* curA = headA, *curB = headB; //遍历int lenA = 0, lenB = 0; //记录两个链表的长度while(curA->next){lenA++;curA = curA->next;}while(curB->next){lenB++;curB = curB->next;}if(curA != curB)return NULL; //若两个结点的地址不同,则表示不相交,return NULLListNode* longer = headA, *shorter = headB; //先假设链表A长于链表Bif(lenB > lenA){ //若是假设错误则交换longer = headB;shorter = headA;}int gap = abs(lenA - lenB); //求出两个链表的长度差while(gap--)longer = longer->next; //先让长的链表走gap步,使得两链表位于同一起跑线while(longer != shorter) //一同往后走,寻找两链表的交点(此时一定相交) {longer = longer->next;shorter = shorter->next;}return longer;}
};
以上就是本文所要描述的所有内容,感谢您对本文的观看,如有疑问请于评论区留言或者私信我都可以🍀