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辅助器免费,wepoker怎么看牌型,方案教程(有挂方针)wepoker怎...
三分钟辅助!wepoker作弊... 三分钟辅助!wepoker作弊方法,德普之星私人局辅助器,手筋教程(有挂透视)1、德普之星私人局辅助...
第七分钟辅助!智星菠萝有挂吗,... 第七分钟辅助!智星菠萝有挂吗,智星德州可以透视吗,诀窍教程(有挂规律)该软件可以轻松地帮助玩家将智星...
第5分钟辅助!hhpoker作... 第5分钟辅助!hhpoker作弊码,hh poker透视器下载,课程教程(有挂秘笈)1、hh pok...
一分钟辅助!wpk俱乐部有没有... 一分钟辅助!wpk俱乐部有没有辅助,wepoker私人局辅助挂,诀窍教程(有挂解密)1、下载好wpk...
第2分钟辅助!sohoo竞技联... 第2分钟辅助!sohoo竞技联盟辅助器,pokermaster辅助器,手筋教程(有挂神器)1、soh...
第六分钟辅助!htx矩阵wep... 第六分钟辅助!htx矩阵wepoker辅助,hhpkoer辅助挂是真的吗,指南教程(有挂解密)1、游...
第七分钟辅助!哈糖大菠萝可以开... 第七分钟辅助!哈糖大菠萝可以开挂吗,佛手大菠萝有挂吗,技法教程(有挂详情)哈糖大菠萝可以开挂吗脚本下...
3分钟辅助!pokemmo手机... 3分钟辅助!pokemmo手机版透视脚本,xpoker辅助助手,指南书教程(有挂头条)1、pokem...
6分钟辅助!wepoker好友... 6分钟辅助!wepoker好友局透视,wepoker怎么挂底牌,指引教程(有挂攻略)1、wepoke...