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)

相关内容

热门资讯

大纲f辅助!wpk俱乐部有没有... 大纲f辅助!wpk俱乐部有没有辅助,wepoker祈福有用吗,必备教程(有挂详情)1、该软件可以轻松...
方针f辅助!红龙poker辅助... 方针f辅助!红龙poker辅助器免费观看,wepoker插件下载,解迷教程(有人有挂)1、许多玩家不...
手册f辅助!大菠萝789辅助器... 手册f辅助!大菠萝789辅助器下载,wepoker破解器,专业教程(有挂细节)1、每一步都需要思考,...
策略f辅助!wepoker怎么... 策略f辅助!wepoker怎么拿到好牌,aapoker透视插件,详细教程(有挂攻略)1)wepoke...
法子f辅助!wepoker辅助... 法子f辅助!wepoker辅助器激活码,聚星ai辅助工具下载,详细教程(竟然有挂)1、玩家可以在聚星...
手筋f辅助!xpoker怎么作... 手筋f辅助!xpoker怎么作弊,wejoker手机版透视脚本,详情教程(有挂方针)1、wejoke...
讲义f辅助!wepokerpl... 讲义f辅助!wepokerplus开挂,wepoker辅助工具,普及教程(揭秘有挂)1、不需要AI权...
学习f辅助!pokemomo辅... 学习f辅助!pokemomo辅助软件,newpoker脚本,分享教程(真的有挂)1、每一步都需要思考...
经验f辅助!aapoker辅助... 经验f辅助!aapoker辅助工具安全吗,sohoopoker辅助,有挂教程(有挂解密)暗藏猫腻,小...
模块f辅助!wepoker怎么... 模块f辅助!wepoker怎么挂飞机,hhpkoer辅助器视频,有挂教程(发现有挂)1、实时hhpk...