当前位置: 首页 > news >正文

C++/JavaScript ⭐算法OJ⭐ 链表相交

题目 160. Intersection of Two Linked Lists

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at node c1:
intersection of Two Linked Lists

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

Note that the linked lists must retain their original structure after the function returns.

给定两个单链表的头节点 headAheadB,返回两个链表相交的节点。如果两个链表没有相交,则返回 null

解题思路

双指针法

使用两个指针 pApB 分别从 headAheadB 开始遍历链表。

pA 到达链表末尾时,将其重定向到 headB;当 pB 到达链表末尾时,将其重定向到 headA

如果两个链表相交,pApB 会在相交节点相遇;如果不相交,pApB 会同时到达链表末尾(即 null)。

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == nullptr || headB == nullptr) return nullptr;

        ListNode *pA = headA;
        ListNode *pB = headB;

        while (pA != pB) {
            pA = (pA == nullptr) ? headB : pA->next;
            pB = (pB == nullptr) ? headA : pB->next;
        }

        return pA;
    }
};
class ListNode {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

/**
 * @param {ListNode} headA
 * @param {ListNode} headB
 * @return {ListNode}
 */
var getIntersectionNode = function(headA, headB) {
    if (headA === null || headB === null) return null;

    let pA = headA;
    let pB = headB;

    while (pA !== pB) {
        pA = (pA === null) ? headB : pA.next;
        pB = (pB === null) ? headA : pB.next;
    }

    return pA;
};

复杂度分析

  • 时间复杂度:O(m + n),其中 mn 分别是两个链表的长度。两个指针最多遍历 m + n 个节点。

  • 空间复杂度:O(1),只使用了常数级别的额外空间。

http://www.dtcms.com/a/34076.html

相关文章:

  • C++ 游戏开发:从零到英雄的进阶之旅
  • [ComfyUI]Recraft贴图开源方案,实现服装印花自由
  • Debezium 报错:“The db history topic is missing” 的处理方法
  • Fences 5深度解析:一键打造超高效整洁桌面
  • QT中经常出现的用法:组合
  • iTHOR 虚拟环境简述
  • 使用matplotlib绘制柱状图并在下面使用表格显示数值
  • 【爬虫】request库
  • MySQL面试学习
  • system verilog的流操作符
  • 使用 DeepSeek 和 Google Gemini 算命
  • Python的子线程与主线程之间的通信并通知主线程更新UI
  • LabVIEW齿轮箱故障分析系统
  • 基于WOA鲸鱼优化的BiLSTM双向长短期记忆网络序列预测算法matlab仿真,对比BiLSTM和LSTM
  • 一篇docker从入门到精通
  • deepseek本地部署,ragflow,docker
  • 【对话推荐系统】Towards Topic-Guided Conversational Recommender System 论文阅读
  • (五)趣学设计模式 之 建造者模式!
  • TileGenie_v1.3.0.1安装包
  • 【Transformer架构】
  • leetcode 119. 杨辉三角 II
  • 【EB-03】 AUTOSAR builder与EB RTE集成
  • 【框架】参考 Spring Security 安全框架设计出,轻量化高可扩展的身份认证与授权架构
  • MySQL要点总结二
  • LangChain大模型应用开发:构建Agent智能体
  • Ubuntu:wvp-GB28181-pro安装、运行
  • 单入单出队列性能优化(Lock-Free)
  • 异常处理在 Promptic 中怎么实现?
  • 基于Springboot医院预约挂号小程序系统【附源码】
  • 【工作流】Spring Boot 项目与 Camunda 的整合