打卡第十二天:寻找链表相交节点

该算法首先计算两个链表的长度,然后确定较短链表,使两者对齐。通过长度差值调整长链表的位置,之后同时遍历两个链表,直到找到相同的节点,即为交点。若未找到交点,则返回NULL。时间复杂度为O(n+m),空间复杂度为O(1)。

题目描述

在这里插入图片描述

思路:

就是找两个链表相同的一个节点,需要注意的是由于两个链表的长度可能不相等,因此要找到链表长度的差值,让长链表找差值步数到与短链表对齐。为什么要这样呢,因为链表后面都是连着的,在前面就出现相同节点的情况其实是不合理的,因为链表不够长。 所以我们遍历一下找到差值就好了。

时间复杂度:O(n + m)
空间复杂度:O(1)
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) 
{
     typedef struct ListNode Node;
     Node* tempLong;
     Node* tempShort;
     int lenA=0;
     int lenB=0;
     int gap=0;
     
     
     tempLong=headA;
     while(tempLong)
     {
         lenA++;
         tempLong=tempLong->next;
     }   

     
     tempLong=headB;
     while(tempLong)
     {
         lenB++;
         tempLong=tempLong->next;
     }

     if(lenA>lenB)
     {
         tempLong=headA;
         tempShort=headB;
         gap=lenA-lenB;
     }
     else
     {
         tempLong=headB;
         tempShort=headA;
         gap=lenB-lenA;
     }

     while(gap--)
     {
         tempLong=tempLong->next;
     }

     while(tempLong&&tempShort)
     {
         if(tempLong==tempShort)
         {
             return tempLong;
         }
         else
         {
               tempLong=tempLong->next;
               tempShort=tempShort->next;
         }
     }

     return NULL;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值