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)

相关内容

热门资讯

科普透视!we poker免费... 科普透视!we poker免费辅助器,德州透视hhpoker,妙招教程(今日头条)-哔哩哔哩1、we...
总结透视!约局吧app有挂吗!... 总结透视!约局吧app有挂吗!确实存在有辅助神器(有挂细节)-哔哩哔哩1、约局吧app有挂吗公共底牌...
实测发现!衢州都莱辅助器,hh... 实测发现!衢州都莱辅助器,hhpoker免费透视脚本,手筋教程(有挂解密)-哔哩哔哩衢州都莱辅助器是...
有挂透视!wpk德州局透视,w... 有挂透视!wpk德州局透视,wepoker有没有透视方法,大纲教程(有人有挂)-哔哩哔哩1)wepo...
解谜透视!sohoopoker... 解谜透视!sohoopoker辅助!一贯一直总是有辅助软件(今日头条)-哔哩哔哩1、许多玩家不知道s...
2分钟细说!钱塘十水三辅助,w... 2分钟细说!钱塘十水三辅助,wepoker透视有用吗,练习教程(有挂细节)-哔哩哔哩1)钱塘十水三辅...
有挂透视!hhpoker辅助器... 有挂透视!hhpoker辅助器视频,pokemomo辅助工具,学习教程(详细教程)-哔哩哔哩1)hh...
有挂透视!菠萝辅助器免费版的特... 有挂透视!菠萝辅助器免费版的特点!一贯真的有辅助app(有挂头条)-哔哩哔哩;菠萝辅助器免费版的特点...
每日必看教程!多乐小程序辅助器... 每日必看教程!多乐小程序辅助器免费,werplan有挂吗,练习教程(有挂教程)-哔哩哔哩1、玩家可以...
开挂透视!hhpoker必备开... 开挂透视!hhpoker必备开挂,wepoker怎么增加运气,大纲教程(有挂详细)-哔哩哔哩1、下载...