⭐算法OJ⭐找到链表的中间节点【快慢指针】(C++实现)Middle of the Linked List

876. Middle of the Linked List

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

复制代码
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

复制代码
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

问题描述

给定一个单链表的头节点 head,返回链表的中间节点。如果链表有两个中间节点(即链表长度为偶数),则返回第二个中间节点。

解题思路

要找到链表的中间节点,可以使用 快慢指针法

  • 使用两个指针,一个快指针(每次走两步)和一个慢指针(每次走一步)。
  • 当快指针到达链表末尾时,慢指针正好指向链表的中间节点。
  • 如果链表长度为偶数,慢指针会指向第二个中间节点。

C++ 实现

cpp 复制代码
// 链表节点定义
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

// 找到链表的中间节点
ListNode* middleNode(ListNode* head) {
    ListNode* slow = head; // 慢指针
    ListNode* fast = head; // 快指针

    while (fast && fast->next) {
        slow = slow->next;         // 慢指针走一步
        fast = fast->next->next;   // 快指针走两步
    }

    return slow; // 慢指针指向中间节点
}

复杂度分析

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n 是链表的节点数。
    • 快指针遍历链表一次,时间复杂度为 O ( n ) O(n) O(n)。
  • 空间复杂度: O ( 1 ) O(1) O(1),只使用了常数级别的额外空间。

总结

通过快慢指针法,我们可以高效地找到链表的中间节点。这种方法不仅代码简洁,而且性能优秀,适合处理大规模数据。掌握快慢指针的思想对于解决类似的链表问题非常有帮助。

相关推荐
一条大祥脚7 分钟前
26杭电暑期第八场(后半)快读|快写|tarjan|路径DP|mex转化|扫描线|前缀和|二分图
数据结构·算法·tarjan·杭电多校·强联通分量·动态规划dp
奈斯先生Vector10 分钟前
从“能调用”到“可运营”:AI Agent 进入多模型时代后的架构升级
java·javascript·数据库·人工智能·算法·架构·aigc
Escalating_xu11 分钟前
【C++类和对象(上)】从类的定义、封装与对象模型到内存对齐和 this 指针
开发语言·前端·c++
吃着火锅x唱着歌14 分钟前
Effective C++ 学习笔记 条款45 运用成员函数模板接受所有兼容类型
c++·笔记·学习
2601_9561219722 分钟前
Bellman-ford算法
算法
爱和冰阔落26 分钟前
【Linux】多线程打印为什么会乱?pthread 创建、等待、退出、取消与分离全实战
linux·运维·c++·redis
叠层归一研究院28 分钟前
基于区分本源的此刻存在唯一性本体论推演
人工智能·算法
luj_176829 分钟前
尾椎藏今生记忆?骨盆对应不确定性
开发语言·网络·c++·经验分享·算法
深圳多奥智能一卡(码、脸)通系统30 分钟前
智能梯控SDK可直接用于第三方开发对接的接口文档说明书
服务器·前端·算法