当前位置: 首页 > 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),只使用了常数级别的额外空间。

相关文章:

  • 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架构】
  • 网站更多分享怎么做/百度游戏风云榜
  • 重庆企业官网建站快速搭建/中国十大电商培训机构
  • 网站建设开发公司地址/网上如何推广自己的产品
  • wordpress 前台删除评论/平台seo
  • 专业网站制作的公司/合肥百度搜索排名优化
  • 上海宝山网站制作/外贸google推广