# Leetcode 解題速記 876. Middle of the Linked List ###### tags: `LeetCode` `C++` 題敘: --- 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. ![](https://i.imgur.com/tFFDKLO.png) ![](https://i.imgur.com/XGPTgMz.png) 測資範圍: --- * The number of nodes in the list is in the range [1, 100]. * 1 <= Node.val <= 100 解題筆記: --- 本題使用C的struct實作linked list,以及龜兔賽跑演算法(雙指針) `struct ListNode *next` 儲存的是linked list中下一筆資料的Address 因此只要開頭將slow、fast兩個指針初始化成第一個Address(`*head`) **使用->運算子(等同於`(*fast).next`)** fast一次前進兩個Address、反之slow一次只前進一個Address 當fast走到linked list末位,即NULL時終止迴圈 此時slow會剛好是linked list中的middleNode return slow即可 程式碼: --- ```c= /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* middleNode(struct ListNode* head){ struct ListNode* fast=head; struct ListNode* slow=head; while(fast!=NULL && fast->next!=NULL){ fast=fast->next->next; slow=slow->next; } return slow; } ```