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)

相关内容

热门资讯

黑科技私人局!wepower透... 黑科技私人局!wepower透视外挂,aapoker辅助工具存在,细节方法(有挂助手)-哔哩哔哩;一...
6分钟知晓!wpk透视脚本,w... 6分钟知晓!wpk透视脚本,wepoker有脚本吗(透视)新2025版(有挂神器)1、wepoker...
玩家亲测!搜索词,wpk德州a... 玩家亲测!搜索词,wpk德州ai机器人,细节揭秘(有挂技术)-哔哩哔哩;wpk德州ai机器人软件透明...
第八分钟普及!hh poker... 第八分钟普及!hh poker软件,wepoker买脚本靠谱吗(透视)可靠技巧(有挂教学)1、超多福...
黑科技游戏!aapoker发牌... 黑科技游戏!aapoker发牌逻辑,德州游戏辅助器,揭秘教程(有挂教程)-哔哩哔哩;1、完成德州游戏...
第3分钟透明挂!hhpoker... 第3分钟透明挂!hhpoker透视挂码怎么用,hhpoker辅助软件下载(透视)力荐教程(有挂技巧)...
推荐一款!德州ai辅助神器ap... 推荐一款!德州ai辅助神器app,微扑克真的有辅助,扑克教程(有挂方针)-哔哩哔哩;亲,有的,ai轻...
第1分钟黑科技!pokemmo... 第1分钟黑科技!pokemmo内置修改器,wepokerplus万能挂(透视)wepoke教程(有挂...
分享实测!德州可能有外挂,wo... 分享实测!德州可能有外挂,wopoker分析器,力荐教程(有挂详细)-哔哩哔哩;德州可能有外挂免费下...
十分钟精通!wepoker透视... 十分钟精通!wepoker透视底牌脚本,aapoker怎么设置提高好牌几率(透视)必备教程(有挂方法...