【每天学习一点算法 2026/03/08】相交链表

每天学习一点算法 2026/03/08

题目:相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

  1. 我们可以先遍历一个链表将所有节点都存放在 Set 集合中,然后遍历另外一个链表遇到相同节点则表示这就是相交起始节点,如果没有相同节点则表示不存在相交节点。

    typescript 复制代码
    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     val: number
     *     next: ListNode | null
     *     constructor(val?: number, next?: ListNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.next = (next===undefined ? null : next)
     *     }
     * }
     */
    
    function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
      const set = new Set()
      while (headA) {
        set.add(headA)
        headA = headA.next
      }
      while (headB) {
        if (set.has(headB)) {
          return headB
        }
        headB = headB.next
      }
      return null
    };
  2. 双指针解法

    我们看图中这种情况,我们可以看出

    用一个指针遍历A链表,然后再遍历B链表,第二次到达相交节点的需要遍历的次数

    和

    用一个指针遍历B链表,然后再遍历A链表,第二次到达相交节点的需要遍历的次数

    是相等的

    所以我们可以用两个指针分别遍历 A → B 和 B → A,两个指针节点第一次相遇的节点就是相交的起始节点,如果两个指针都遍历完了还没相遇那就没有相交节点。

    typescript 复制代码
    function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
      let tempA = headA
      let tempB = headB
      while (tempA != tempB) {
        tempA = tempA == null ? headB : tempA.next
        tempB = tempB == null ? headA : tempB.next
      }
      return tempA
    };

题目来源:力扣(LeetCode)

相关推荐
ZhengEnCi18 分钟前
同样的模型,为什么本地和云 API 差别那么大:量化精度、聊天模板与采样参数的三大元凶
人工智能·算法·llm
Flynn Liang38 分钟前
RAG 答非所问/幻觉怎么破?Spring AI QuestionAnswerAdvisor 召回优化实战(TopK/重排/混合检索)
人工智能·算法·spring·rag·幻觉·springai
海海不掉头发1 小时前
CSDN博客_时序预测9模型复现对比
人工智能·学习·软件工程
liminla!1 小时前
SQL 从入门到进阶:语法速查与实战练习(完整优化版)
数据库·sql·算法
维克兜率天2 小时前
【维克】指数调整:哪些股票会被“强制买入“?
人工智能·python·算法
蓝祁子yoky3 小时前
Qt学习日记 Day13:网络编程(一)-TCP基础与Socket实战
网络·qt·学习
罗西的思考3 小时前
【轻量化复刻大模型】线性注意力交互式演示
人工智能·算法·机器学习
神也畏惧菠萝3 小时前
Day08 Python流程控制从入门到上瘾:if/match/while/for四件套,从B站登录一路打到猜数字游戏
python·算法·数据存储·for·while·if·ifelse
揽星河..3 小时前
【C语言】分支和循环
c语言·c++·算法