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)

相关内容

热门资讯

据文件显示!德州透视hhpok... 据文件显示!德州透视hhpoker,欢乐达人暗宝怎么获得,竟然真的有辅助app(哔哩哔哩)欢乐达人暗...
揭幕透视!哈糖大菠萝能开挂吗,... 揭幕透视!哈糖大菠萝能开挂吗,werplan辅助软件(透视)总是是有辅助脚本(哔哩哔哩)1、哈糖大菠...
透视方案!hhpoker德州有... 透视方案!hhpoker德州有挂吗(透视)切实是真的辅助平台(哔哩哔哩)hhpoker德州有挂吗是不...
有了最新消息!wepoker开... 有了最新消息!wepoker开辅助能查到吗,威信茶馆透视挂,都是是真的有辅助技巧(哔哩哔哩)1、操作...
辅助透视!pokemmo脚本,... 辅助透视!pokemmo脚本,来玩app破解(透视)本来一直都是有辅助工具(哔哩哔哩)来玩app破解...
透视方式!werplan有挂吗... 透视方式!werplan有挂吗(透视)果然存在有辅助神器(哔哩哔哩)1、werplan有挂吗公共底牌...
随着!wpk德州局透视,吉安小... 随着!wpk德州局透视,吉安小程序中至游戏辅助,一直真的有辅助插件(哔哩哔哩)1、吉安小程序中至游戏...
必备透视!菠萝德州透视脚本,约... 必备透视!菠萝德州透视脚本,约局吧怎么看有没有挂(透视)一直是有辅助方法(哔哩哔哩)1、游戏颠覆性的...
透视步骤!hhpoker免费辅... 透视步骤!hhpoker免费辅助器(透视)本来存在有辅助安装(哔哩哔哩)一、hhpoker免费辅助器...
解迷透视!pokermaste... 解迷透视!pokermaster修改器,uupoker透视(透视)果然真的有辅助app(哔哩哔哩)p...