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

本文介绍了一种高效算法来找到两个链表的第一个公共节点,通过双指针技巧实现O(n)的时间复杂度和O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

160.相交链表

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

如下面的两个链表:
在这里插入图片描述
在节点 c1 开始相交。

示例 1:
在这里插入图片描述

输入: 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:

在这里插入图片描述

输入: 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 个节点。

示例 3:

在这里插入图片描述

输入: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出: null
输入解释: 从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释: 这两个链表不相交,因此返回 null。

注意:

  • 如果两个链表没有交点,返回 null.
  • 在返回结果后,两个链表仍须保持原有的结构。
  • 可假定整个链表结构中没有循环。
  • 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

本题与主站 160 题相同:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/

解题思路

  1. 用两个指针分别从两个链表头部开始扫描,每次分别走一步;
  2. 如果指针走到null,则从另一个链表头部开始走;
  3. 当两个指针相同时,
    • 如果指针不是null,则指针位置就是相遇点;
    • 如果指针是 null,则两个链表不相交;

我还是别偷懒画个图吧,一目了然:

1. 两个链表不相交:

在这里插入图片描述

a,b分别代表两个链表的长度,则第一个指针走了a + b步,第二个指针走了b + a步,即两个指针分别走 a+b 步后都变成 nullJava中用“==”判断两个null是否相等会返回true

2. 两个链表相交:

在这里插入图片描述

  • a = b a = b a=b 时,两个指针都走了a步就相遇了。
  • a ≠ b a \not= b a=b 时,第一个指针走了a + c + b步,第二个指针走了b + c + a步,即两个指针分别走 a + b + c步后在两链表交汇处相遇。

时间复杂度: 每个指针走的长度不大于两个链表的总长度,所以时间复杂度是 O ( n ) O(n) O(n)

Java代码

/**
 * 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 cur1 = headA,cur2 = headB;

        //cur1走到尽头时,再从headB开始走,cur2走到尽头时,再从headA开始走
        //最后cur1和cur2要么在相交点相遇,要么在结尾的null相遇
        //两个null用==判断也会返回true
        while(cur1 != cur2){
            cur1 = cur1 == null ? headB : cur1.next;
            cur2 = cur2 == null ? headA : cur2.next;
        }
        return cur1;
    }
}

在这里插入图片描述

Go代码

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func getIntersectionNode(headA, headB *ListNode) *ListNode {
    //cur1走到尽头时,再从headB开始走,cur2走到尽头时,再从headA开始走
    //最后cur1和cur2要么在相交点相遇,要么在结尾的null相遇
    if headA == nil || headB == nil {
        return nil
    }

    cur1,cur2 := headA,headB
    for cur1 != cur2 {
        if cur1 == nil {
            cur1 = headB
        } else {
            cur1 = cur1.Next
        }

        if cur2 == nil {
            cur2 = headA
        } else {
            cur2 = cur2.Next
        }
    }
    
    return cur1
}

在这里插入图片描述

### 找到两个链表第一个公共节点 #### 方法一:哈希集合 (基于引用[^1]) 通过使用 `Map` 或者 `Set` 数据结构来存储其中一个链表的所有节点。随后遍历另一个链表,检查当前节点是否已经存在于集合中。如果存在,则该节点即为两链表第一个公共节点。 这种方法的时间复杂度为 \(O(m+n)\),其中 \(m\) 和 \(n\) 是两条链表的长度;空间复杂度为 \(O(m)\) 或 \(O(n)\),取决于哪个链表被存入集合中。 ```python def getIntersectionNode(headA, headB): nodes_in_B = set() current_node = headB while current_node is not None: nodes_in_B.add(current_node) current_node = current_node.next current_node = headA while current_node is not None: if current_node in nodes_in_B: return current_node current_node = current_node.next return None ``` --- #### 方法二:双指针法 (基于引用[^2]) 定义两个指针分别指向两个链表头结点。每次移动一步,当到达链表末端时,跳转至另一条链表头部继续前进。这样可以消除两者之间的长度差,在第二次相遇处即是第一个公共节点。 此方法时间复杂度同样为 \(O(m+n)\),而空间复杂度降为了 \(O(1)\)。 ```python def getIntersectionNode(headA, headB): pointerA, pointerB = headA, headB while pointerA != pointerB: pointerA = headB if pointerA is None else pointerA.next pointerB = headA if pointerB is None else pointerB.next return pointerA # 返回值可能是公共节点或者None ``` --- #### 方法三:计算长度差异并调整起始位置 先遍历两条链表得到它们各自的长度,并求出差值。让较长的那个链表先行走这个差距步数后再同步逐一遍历比较各对应节点直至发现相等为止。 这种方式也实现了线性时间和常量级额外内存消耗的目标。 ```python def length(node): count = 0 while node: count += 1 node = node.next return count def getIntersectionNode(headA, headB): lenA, lenB = length(headA), length(headB) shorter = headA if lenA < lenB else headB longer = headB if lenA < lenB else headA diff = abs(lenA - lenB) for _ in range(diff): longer = longer.next while shorter and longer: if shorter == longer: return shorter shorter = shorter.next longer = longer.next return None ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值