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辅助!wepoker透视... 阶段f辅助!wepoker透视方法,hhpoker德州有挂吗,解密教程(有挂工具)hhpoker德州...
诀窍f辅助!hhpoker德州... 诀窍f辅助!hhpoker德州作弊,wejoker手机版透视脚本,关于教程(讲解有挂)1、首先打开w...
教材f辅助!werplan怎么... 教材f辅助!werplan怎么透视,悟空黑桃a有挂嘛,解密教程(讲解有挂)1、悟空黑桃a有挂嘛公共底...
诀窍f辅助!如何下载wepok... 诀窍f辅助!如何下载wepoker安装包,hhpoker德州真的假的,分享教程(有挂透视)如何下载w...
总结f辅助!wepoker辅助... 总结f辅助!wepoker辅助器怎么弄,pokernow辅助工具,推荐教程(确实有挂)进入游戏-大厅...
要领f辅助!约局吧游戏挂,xp... 要领f辅助!约局吧游戏挂,xpoker怎么作弊,辅助教程(真实有挂)1、进入到约局吧游戏挂是否有挂之...
总结f辅助!德州私人局脚本,a... 总结f辅助!德州私人局脚本,aapoker破解侠是真的吗,关于教程(有挂解密)1、上手简单,内置详细...
绝活f辅助!wepoker轻量... 绝活f辅助!wepoker轻量版辅助,hhpoker透视工具,解迷教程(有挂猫腻)一、wepoker...
大纲f辅助!拱趴大菠萝挂哪里,... 大纲f辅助!拱趴大菠萝挂哪里,wepoker线上大神,普及教程(有挂存在)1、在拱趴大菠萝挂哪里插件...
技法f辅助!哈糖大菠萝能开挂吗... 技法f辅助!哈糖大菠萝能开挂吗,hhpoker德州机器人,曝光教程(有挂分析)1、上手简单,内置详细...