欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > LeetCode160 相交链表

LeetCode160 相交链表

2024/10/23 23:19:43 来源:https://blog.csdn.net/daishabby2486/article/details/140694091  浏览:    关键词:LeetCode160 相交链表

前言

题目: 160. 相交链表
文档: 代码随想录——链表相交
编程语言: C++
解题状态: 没思路…

思路

依旧是双指针法,很巧妙的方法,有点想不出来。

代码

先将两个链表末端对齐,然后两个指针齐头并进,容易判断出是否相交。

/*** 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;ListNode* curB = headB;int lenA = 0;int lenB = 0;while (curA) {++lenA;curA = curA -> next;}while (curB) {++lenB;curB = curB -> next;}curA = headA;curB = headB;if (lenB > lenA) {swap(lenA, lenB);swap(curA, curB);}int gap = lenA - lenB;while (gap--) {curA = curA -> next;}while (curA) {if (curA == curB) {return curA;}curA = curA -> next;curB = curB -> next;}return NULL;}
};
  • 时间复杂度: O ( m + n ) O(m + n) O(m+n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

版权声明:

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

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