|
| 1 | +--- |
| 2 | +description: 'Author: @wingkwong | https://leetcode.com/problems/middle-of-the-linked-list/description/' |
| 3 | +tags: [Linked List, Two Pointers] |
| 4 | +--- |
| 5 | + |
| 6 | +# 0876 - Middle of the Linked List (Easy) |
| 7 | + |
| 8 | +## Problem Link |
| 9 | + |
| 10 | +https://leetcode.com/problems/middle-of-the-linked-list/description/ |
| 11 | + |
| 12 | +## Problem Statement |
| 13 | + |
| 14 | +Given the `head` of a singly linked list, return *the middle node of the linked list*. |
| 15 | + |
| 16 | +If there are two middle nodes, return **the second middle** node. |
| 17 | + |
| 18 | +**Example 1:** |
| 19 | + |
| 20 | +``` |
| 21 | +Input: head = [1,2,3,4,5] |
| 22 | +Output: [3,4,5] |
| 23 | +Explanation: The middle node of the list is node 3. |
| 24 | +``` |
| 25 | + |
| 26 | +**Example 2:** |
| 27 | + |
| 28 | +``` |
| 29 | +Input: head = [1,2,3,4,5,6] |
| 30 | +Output: [4,5,6] |
| 31 | +Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. |
| 32 | +``` |
| 33 | + |
| 34 | +**Constraints:** |
| 35 | + |
| 36 | +- The number of nodes in the list is in the range `[1, 100]`. |
| 37 | +- `1 <= Node.val <= 100` |
| 38 | + |
| 39 | +## Approach 1: Fast and Slow Pointer |
| 40 | + |
| 41 | +Classic Fast and Slow Pointer question |
| 42 | + |
| 43 | +- Time Complexity: $O(N)$ where $N$ is the number of nodes |
| 44 | +- Space Complexity: $O(1)$ |
| 45 | + |
| 46 | +<Tabs> |
| 47 | +<TabItem value="cpp" label="C++"> |
| 48 | +<SolutionAuthor name="@wingkwong"/> |
| 49 | + |
| 50 | +```cpp |
| 51 | +/** |
| 52 | + * Definition for singly-linked list. |
| 53 | + * struct ListNode { |
| 54 | + * int val; |
| 55 | + * ListNode *next; |
| 56 | + * ListNode() : val(0), next(nullptr) {} |
| 57 | + * ListNode(int x) : val(x), next(nullptr) {} |
| 58 | + * ListNode(int x, ListNode *next) : val(x), next(next) {} |
| 59 | + * }; |
| 60 | + */ |
| 61 | +class Solution { |
| 62 | +public: |
| 63 | + ListNode* middleNode(ListNode* head) { |
| 64 | + // fast & slow pointer |
| 65 | + // slow moves 1 step |
| 66 | + // fast moves 2 steps |
| 67 | + // 1 -> 2 -> 3 -> 4 -> 5 |
| 68 | + // slow : 1 -> 2 -> 3 |
| 69 | + // fast : 1 -> 3 -> 5 |
| 70 | + // when fast reaches the end, slow will be the middle |
| 71 | + ListNode* slow = head; |
| 72 | + ListNode* fast = head; |
| 73 | + while (fast != NULL && fast->next != NULL) { |
| 74 | + slow = slow->next; |
| 75 | + fast = fast->next->next; |
| 76 | + } |
| 77 | + return slow; |
| 78 | + } |
| 79 | +}; |
| 80 | +``` |
| 81 | +
|
| 82 | +</TabItem> |
| 83 | +</Tabs> |
0 commit comments