
In embedded systems programming, resource management and algorithmic efficiency are paramount. When working with dynamic data structures like Linked Lists, a common requirement is to find the middle node—whether for splitting the list in Merge Sort or for specific data processing tasks.
While the naive approach involves two passes (counting then traversing), there is a much more elegant and efficient solution: the Two-Pointer Technique, also known as Floyd’s Cycle-Finding Algorithm variation.
The concept is simple: we use two pointers, slow and fast.
By the time the fast pointer reaches the end of the list, the slow pointer will be exactly at the middle. This allows us to find the middle in a single pass with O(n) time complexity and O(1) space complexity.
Here is the clean implementation of the findMiddle function:
struct ListNode* findMiddle(struct ListNode *head) {if (head == NULL) return NULL;struct ListNode *slow = head;struct ListNode *fast = head;// Move fast by 2 steps and slow by 1 stepwhile (fast != NULL && fast->next != NULL) {slow = slow->next;fast = fast->next->next;}return slow; // This is the Middle node}
Let’s visualize the process with a list of 5 nodes: 1 → 2 → 3 → 4 → 5
| Step | Slow Pointer | Fast Pointer |
|---|---|---|
| 0 | Node 1 | Node 1 |
| 1 | Node 2 | Node 3 |
| 2 | Node 3 | Node 5 |
| 3 | Node 3 | -- |
For an even-length list (e.g., 1 → 2 → 3 → 4):
while (fast->next != NULL && fast->next->next != NULL)In embedded environments (like STM32 or ESP32 development), you often deal with:
Finding the middle of a linked list is a fundamental building block for more complex algorithms. By using the Two-Pointer approach, you ensure your embedded application remains fast and memory-efficient.
Quick Links
Legal Stuff





