最近在复习数据结构,复习完c语言的单链表后,想着上leetcode上做一下题,然后就是这道
给定两个单链表的头节点 headA
和 headB
,请找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
。
图示两个链表在节点 c1
开始相交:
题目数据 保证 整个链式结构中不存在环。
注意,函数返回结果后,链表必须 保持其原始结构 。
示例 1:
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Intersected at '8' 解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。 从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。 在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
示例 2:
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 输出:Intersected at '2' 解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。 从各自的表头开始算起,链表 A 为 [0,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 。
提示:
listA
中节点数目为m
listB
中节点数目为n
0 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
- 如果
listA
和listB
没有交点,intersectVal
为0
- 如果
listA
和listB
有交点,intersectVal == listA[skipA + 1] == listB[skipB + 1]
看到题目第一反应,没什么思路,甚至指针的操作也不熟练,想来想去只会用暴力法
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA == NULL && headB == NULL){
return NULL;
}
struct ListNode* currA = headA;
struct ListNode* currB = headB;
while(currA != NULL){
currB = headB;
while(currB != NULL){
if(currA == currB){
return currA;
}
currB = currB->next;
}
currA = currA->next;
}
// if(currB == NULL || currA == NULL) {
// return NULL;
// }
return NULL;
}
通过两层循环,一点一点遍历
然后看了一下官方的,有一个双指针很妙
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if (headA == NULL || headB == NULL) {
return NULL;
}
struct ListNode *pA = headA, *pB = headB;
while (pA != pB) {
pA = pA == NULL ? headB : pA->next;
pB = pB == NULL ? headA : pB->next;
}
return pA;
}
代码高效又简介,两个链表长度不是不一样长,那就用对方的长度来弥补,很妙
然后我又看到一个老哥的更高效率代码,简单,易懂,高效
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* l1=headA,*l2=headB;
int a=1,b=1;
while(l1->next)
{
l1=l1->next;
a++;
}
while(l2->next)
{
l2=l2->next;
b++;
}
if(l1!=l2)
{
return NULL;
}
else
{
l1=headA;
l2=headB;
int dif=abs(a-b);
while(dif--)
{
if(a>b)
{
l1=l1->next;
}
else
{
l2=l2->next;
}
}
while(l1!=l2)
{
l1=l1->next;
l2=l2->next;
}
return l1;
}
}