[Data structure OJ question] The intermediate node of the linked list

Original title link: https://leetcode.cn/problems/middle-of-the-linked-list/description/

Table of contents

1. Description of the topic

2. Thinking analysis

3. Code implementation


1. Description of the topic

2. Thinking analysis

fast and slow pointer method

Find the middle node through the fast and slow pointers. The fast pointer takes two steps each time , and the slow pointer takes one step at a time . When the fast pointer reaches the end, the slow pointer just goes to the middle position .

Here we use slow to represent slow pointers, and fast to represent fast pointers. At the beginning, both slow and fast point to the head node head.

If the singly linked list has an odd number of nodes , when fast->next=NULL , slow points to the intermediate node:

 If the singly linked list has an even number of nodes , when fast==NULL , slow points to the intermediate node:

 

3. Code implementation

/**
 * 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;
}

Guess you like

Origin blog.csdn.net/m0_62531913/article/details/132309395