欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > C++速通LeetCode简单第3题-相交链表

C++速通LeetCode简单第3题-相交链表

2025/11/5 18:47:42 来源:https://blog.csdn.net/weixin_47768406/article/details/142177009  浏览:    关键词:C++速通LeetCode简单第3题-相交链表

 简单解:

/*** 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 *indexA = headA;ListNode *answer = NULL;while(indexA){ListNode *indexB = headB;while(indexB){if(indexA == indexB){answer = indexA;return answer;}indexB = indexB->next;}indexA = indexA->next;}return NULL;}
};

最优解:

class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {if (!headA || !headB) {return NULL;}ListNode *you = headA, *she = headB;while (you != she) { // 若是有缘,你们早晚会相遇you = you ? you->next : headB; // 当你走到终点时,开始走她走过的路she = she ? she->next : headA; // 当她走到终点时,开始走你走过的路}// 如果你们喜欢彼此,请携手一起走完剩下的旅程(将下面这个 while 块取消注释)。// 一路上,时而你踩着她的影子,时而她踩着你的影子。渐渐地,你变成了她,她也变// 成了你。/* while (she) {you = she->next;she = you->next;} */return you;}
};

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词