LeetCode160 相交链表
创始人
2024-11-20 13:35:28
0

前言

题目: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)

相关内容

热门资讯

透视辅助!雀姬辅助(辅助挂)原... 透视辅助!雀姬辅助(辅助挂)原来是真的有挂(详细辅助德州论坛);1、很好的工具软件,可以解锁游戏的雀...
wepoke辅助插件!微扑克w... wepoke辅助插件!微扑克wpk安全吗,(wepoker)确实存在有挂(有挂辅助)这是由厦门游乐互...
透视神器!来玩德州作弊挂,HH... 自定义HHpoker有挂吗?知乎系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
透视辅助!越乡游嵊州辅助(辅助... 透视辅助!越乡游嵊州辅助(辅助挂)都是真的有挂(详细辅助wpk教程)1、越乡游嵊州辅助系统规律教程、...
wepoke辅助插件!约局吧是... wepoke辅助插件!约局吧是正规的吗,(wePoke)其实是真的有挂(有挂软件);亲真的是有正版授...
透视总结!菠萝辅助1.3怎么使... 透视总结!菠萝辅助1.3怎么使用,wepoker透视作弊挂!详细辅助教程(详细辅助普及教程);wep...
透视辅助!汇友游戏辅助(辅助挂... 透视辅助!汇友游戏辅助(辅助挂)都是是真的有挂(详细辅助AI教程)1、用户打开应用后不用登录就可以直...
wepoke有挂!poker ... wepoke有挂!poker world外挂,(wepOKE)原本真的是有挂(有挂透视)这是由厦门游...
透视有挂!wepoker正确养... WePoke高级策略深度解析‌;透视有挂!wepoker正确养号方法,wepoker透视挂试用(详细...
透视辅助!雀友会辅助潮汕麻将脚... 透视辅助!雀友会辅助潮汕麻将脚本(辅助挂)真是存在有挂(详细辅助德州教程);1、雀友会辅助潮汕麻将脚...