【数据结构OJ题】链表的中间结点

原题链接:https://leetcode.cn/problems/middle-of-the-linked-list/description/

目录

1. 题目描述

2. 思路分析

3. 代码实现


1. 题目描述

2. 思路分析

快慢指针法

通过快慢指针找到中间结点,快指针每次走两步慢指针每次走一步当快指针走到结尾的时候,慢指针正好走到中间位置

我们这里用slow表示慢指针,fast表示快指针。一开始让slow和fast都指向头结点head。

如果单链表有奇数个结点,当fast->next=NULL时,slow所指向的就是中间结点:

 如果单链表有偶数个结点,当fast==NULL时,slow所指向的就是中间结点:

3. 代码实现

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* middleNode(struct ListNode* head){
    struct ListNode *slow=head,*fast=head;
    while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;
    }
    return slow;
}

猜你喜欢

转载自blog.csdn.net/m0_62531913/article/details/132309395