--- tags: leetcode --- # [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode *middleNode(ListNode *head) { ListNode *slow = head, *fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; } return slow; } }; ``` ## Time Complexity $O(n)$ $n$ is the number of nodes in the linked list referred by `head`. ## Space Complexity $O(1)$ # Miscellaneous <!-- # Test Cases ``` [1,2,3,4,5] ``` ``` [1,2,3,4,5,6] ``` ``` [1] ``` ``` [1,2] ``` -->