How to Compute the Middle of the Linked List using Fast and Slow Pointer?


Given a non-empty, singly linked list with head node head, return a middle node of linked list. If there are two middle nodes, return the second middle node.

Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])

The returned node has value 3. (The judge’s serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.

Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.

Note:
The number of nodes in the given list will be between 1 and 100.

Intuitive Algorithm: Converting to Vector/Array

The most intuitive approach is to first convert the Linked List into array/vector. The std::list internally is implemented using linked structure and hence is not suitable. Converting a linked list to array or vector requires O(N) space – obviously and O(N) time to go through the list in the worst case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        vector<ListNode*> data;
        if (head == nullptr) return nullptr;
        while (head != nullptr) {
            data.push_back(head);
            head = head->next;
        }
        return data[data.size() / 2];
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        vector<ListNode*> data;
        if (head == nullptr) return nullptr;
        while (head != nullptr) {
            data.push_back(head);
            head = head->next;
        }
        return data[data.size() / 2];
    }
};

Middle of the Linked List via Fast and Slow Pointer Algorithm

Another better approach is O(1) constant space. We just need two pointers: fast and slow. The fast pointer walks two step at a time while the slow pointer walks one step at a time. When the fast pointer reaches the end, the slow pointer is in the middle. The time complexity is O(N).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

Fast and slow pointers are often used to navigate a linked list where you don’t know the size in advance. Similarly, we can have a fast pointer that walks three steps and a slow pointer that walks one step, if you want to get the 1/3 node.

See other implementations of getting the middle of the linked list:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
636 words
Last Post: How to Fix eslint linebreak style error on Visual Studio Code Windows? (Expected linebreaks to be 'crlf' but found 'lf')
Next Post: Counting Substrings with Only One Distinct Letter with Different Algorithms

The Permanent URL is: How to Compute the Middle of the Linked List using Fast and Slow Pointer?

Leave a Reply