【剑指offer】52. 两个链表的第一个公共节点

剑指 Offer 52. 两个链表的第一个公共节点

知识点:链表;

题目描述

输入两个链表,找出它们的第一个公共节点。

如下面的两个链表:

示例

示例1:
image

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A [4,1,8,4,5],链表 B [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

示例2:
image

输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 输出:Reference of the node with value = 2 输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A [0,9,1,2,4],链表 B [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

解法一:解析

我们可以假设链表A独有部分长度为m,链表B独有部分长度为n,两个链表相交部分长度为x,所以链表A的长度为m+x,链表B的长度为n+x。我们定义两个指针从两个链表同时走,A走完后去走B,B走完后去走A,两者速度相同,最后到达相交点处正好碰面。走的距离都是m+n+x;

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; ListNode tempA = headA; ListNode tempB = headB; while(tempA != tempB){ //A走到头就接到B上; tempA = tempA != null ? tempA.next : headB; //B走到头就接到A上; tempB = tempB != null ? tempB.next : headA; } return tempB; } }
  • python
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: tempA = headA tempB = headB while tempA != tempB: tempA = tempA.next if tempA != None else headB tempB = tempB.next if tempB != None else headA return tempA

时间复杂度:O(N);
空间复杂度:O(1);


__EOF__

本文作者Curryxin
本文链接https://www.cnblogs.com/Curryxin/p/15038161.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   Curryxin  阅读(47)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
Live2D
欢迎阅读『【剑指offer】52. 两个链表的第一个公共节点』
点击右上角即可分享
微信分享提示