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)

相关内容

热门资讯

透视攻略!wepoker脚本下... 这是一款非常优秀的wepoker脚本下载 ia辅助检测软件,能够让你了解到wepoker脚本下载中牌...
透视ai!wepoker插件程... 透视ai!wepoker插件程序激活码,南宁友乐辅助(确实真的是有挂);1、许多玩家不知道wepok...
aapoker辅助功能!hhp... aapoker辅助功能!hhpoker外挂靠谱吗,wepoker脚本下载(详细辅助揭秘攻略)aapo...
透视智能ai“wpk辅助器下载... 透视智能ai“wpk辅助器下载”果然是有挂(辅助挂)详细辅助插件教程;1)辅助挂:进一步探索辅助透视...
透视最新!wepoker作弊辅... 透视最新!wepoker作弊辅助,wepoker透视有吗(详细辅助AI教程);wepoker作弊辅助...
透视肯定!德普之星辅助工具如何... 透视肯定!德普之星辅助工具如何打开,天蝎辅助(本来是真的有挂);进入游戏-大厅左侧-新手福利-激活码...
智星德州菠萝安装!wepoke... 智星德州菠萝安装!wepoker辅助器怎么弄,德朴之星脚本(详细辅助力荐教程)是一款可以让一直输的玩...
透视插件“hhpoker透视脚... 透视插件“hhpoker透视脚本视频”其实有挂(辅助挂)详细辅助系统教程;1、进入到黑科技之后,能看...
透视科技!智星德州辅助译码插件... 透视科技!智星德州辅助译码插件靠谱吗,hhpoker智能辅助插件(详细辅助力荐教程);实战中需综合运...
透视了解!wepoker手机版... 透视了解!wepoker手机版辅助,新玄龙辅助(其实存在有挂);1、用户打开应用后不用登录就可以直接...