Find the middle element of a linked list.
Example 1:
Input:
1 2 3 4 5
Output: The middle element is 3
Example 2:
Input: 0
Output: The list is empty.
1. Data Structure:-
A singly linked list is used to store a sequence of nodes, where each node contains an integer value (data)
and a pointer to the next node (next).
2. Find Middle Element:-
The goal of the code is to find the middle element of the linked list, which is the element that is
approximately halfway through the list. This is done by iterating through the list using two pointers, a
slow pointer (slow) and a fast pointer (fast).
3. Initialization:-
The slow and fast pointers are initially set to the head of the linked list (head), which is the starting
point of the list.
4. Traversal:-
Inside the findMiddle function, a while loop is used to traverse the linked list. The loop continues as long
as both the fast pointer and the next of the fast pointer are not nullptr, which means the fast pointer is
not at the end of the list.
In each iteration of the loop, the slow pointer moves one step (slow = slow->next) and the fast pointer
moves two steps (fast = fast->next->next).
6. Find the Middle:-
When the fast pointer reaches the end of the list (or the last valid node in case of an even number of
nodes), the slow pointer will be at the middle element of the linked list. This is because the fast pointer
moves twice as fast as the slow pointer.
7.Output:-
The findMiddle function returns the slow pointer, which points to the middle element.
In the main function, it checks if the middle pointer is not nullptr. If the list is empty, it prints "The
list is empty." Otherwise, it prints the data of the middle element.