🔗 Middle of the Linked List - Solution

LeetCode #876 Difficulty: Easy

Approach

Use the slow and fast pointer (tortoise and hare) technique to find the middle node:

This approach achieves O(1) space complexity with optimal O(n/2) time complexity.


Algorithm Explanation

  1. Initialize Pointers:
    • slow = head (moves one step at a time)
    • fast = head (moves two steps at a time)
  2. Traverse the List:
    • While fast != nullptr AND fast->next != nullptr:
      • Move slow one step forward: slow = slow->next
      • Move fast two steps forward: fast = fast->next->next
  3. Return Result:
    • When loop ends, slow points to the middle node
    • For even-length lists, returns the second middle node

Complexity Analysis


C++ Solution

/**
 * 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;
        ListNode* fast = head;
        while(fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

← Back to Problems Linked List Hub 🏠