[Algorithm] Find merge point of two linked list
Assume we have two linked list, we want to find a point in each list, from which all the the nodes share the same value in both list. Then we call this point is "merge point".
In the iamge, the merge point shoud be Node(7).
// Link A length 4, Link B length 5
// All the node after the merge point should be the same
// based on that, we can make sure that the merge point should
// happens in range [x, c] or [y, c], it is not possible to happen at z
// A x - x - c - c
// B z - y - y - c - c
function Node(val) { return { val, next: null }; } function Link() { return { head: null, tail: null, length: 0, add(val) { const newNode = new Node(val); if (this.length === 0) { this.head = newNode; this.tail = newNode; this.tail.next = null; } else { let temp = this.tail; this.tail = newNode; temp.next = this.tail; } this.length++; } }; } // O ( m + n ), Space: O(1) function findMergePoint(a, b) { // Link A length 4, Link B length 5 // All the node after the merge point should be the same // based on that, we can make sure that the merge point should // happens in range [x, c] or [y, c], it is not possible to happen at z // A x - x - c - c // B z - y - y - c - c let diff, headA = a.head, headB = b.head; if (a.length > b.length) { // O(1) diff = a.length - b.length; [a, b] = [b, a]; } else { diff = b.length - a.length; } // reach +diff step for longer for (let i = 0; i < diff; i++) { headB = headB.next; // O(m) } while (headA != null && headB.val != null ) { // O(n) if (headA.val === headB.val) { return headA; } headA = headA.next; headB = headB.next; } return null; } const lA = new Link(); lA.add(4); lA.add(6); lA.add(7); lA.add(1); const lB = new Link(); lB.add(9); lB.add(3); lB.add(5); lB.add(7); lB.add(1); console.log(findMergePoint(lA, lB)); // Object {val: 7, next: Object}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-04-03 [GraphQL] Fetch Server Data and Client-side State in One Query using React Apollo + GraphQL
2018-04-03 [Angular] Getting to Know the @Attribute Decorator in Angular
2016-04-03 [Angular 2] Async Http