⭐算法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),只使用了常数级别的额外空间。

总结

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

相关推荐
derek19976 小时前
软考软件设计师:B-树和 B+树的区别、线性探查法查找时到底比较了谁
c语言·c++·计算机网络·软件工程·学习方法
fqbqrr7 小时前
2612C++,C++量钢问题
c++
充电zcx8 小时前
C++ 复习:stack、queue 与仿函数——容器适配器、priority_queue 与 deque 的取舍
c++·queue·仿函数·stack·priority_queue
俊俊几年的9 小时前
RK3588 开发板详解:硬件优势与嵌入式 Linux 学习路线
linux·c++·嵌入式
可乐_不渴9 小时前
【C++】 STL篇 哈希表实现
c++·哈希算法·散列表
小O的算法实验室10 小时前
SEVC,城市灾害环境下应急物流的帕累托归档引导式多目标路径规划
算法
维克兜率天10 小时前
【维克】布林带:通道类指标的“量化基石“
人工智能·python·算法
风落青芜10 小时前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
wuyk55511 小时前
AI 时代的嵌入式该怎么学-11-C不是语法是对内存的显式建模
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·算法