【leetcode】Intersection of Two Linked Lists
Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
先从头到尾扫描,看两个链表长度相差多少。
然后让长的链表先走过这个长度差,然后两个链表同时走,直到相遇
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 12 13 14 if(headA==NULL||headB==NULL) 15 { 16 return NULL; 17 } 18 19 ListNode *hA=headA,*hB=headB; 20 21 int lenA=1,lenB=1; 22 while(hA->next!=NULL) 23 { 24 lenA++; 25 hA=hA->next; 26 } 27 28 while(hB->next!=NULL) 29 { 30 lenB++; 31 hB=hB->next; 32 } 33 34 35 if(hA!=hB) 36 { 37 return NULL; 38 } 39 40 int dis=lenA-lenB; 41 42 43 hA=headA; 44 hB=headB; 45 46 if(dis>0) 47 { 48 while(dis) 49 { 50 hA=hA->next; 51 dis--; 52 } 53 } 54 55 if(dis<0) 56 { 57 dis=-dis; 58 while(dis) 59 { 60 hB=hB->next; 61 dis--; 62 } 63 } 64 65 while(hA!=hB) 66 { 67 hA=hA->next; 68 hB=hB->next; 69 } 70 71 72 return hA; 73 } 74 }; 75
分类:
算法研究
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现