middle element in list Algorithm

The middle element in list algorithm is a popular technique used in computer programming to find the middle element of a given list, array or data structure. This algorithm comes in handy when dealing with problems that require identifying the midpoint or center of a dataset, such as a linked list, where direct indexing is not possible. In order to find the middle element, the algorithm typically utilizes two pointers, one moving at a faster rate (two steps at a time) and the other moving at a slower rate (one step at a time). The basic idea behind this approach is that when the faster pointer reaches the end of the list, the slower pointer will have arrived at the middle element, effectively solving the problem in a single traversal of the list. Implementing the middle element in list algorithm involves initializing two pointers, often referred to as 'slow' and 'fast', at the beginning of the list. The algorithm then iterates through the list, moving the slow pointer one step forward and the fast pointer two steps forward at each iteration. When the fast pointer reaches the end of the list, or is unable to move two steps further due to reaching the penultimate element, the slow pointer will be pointing at the middle element of the list. If the list has an even number of elements, there will be two middle elements, and the slow pointer will be pointing at the second middle element. This algorithm is an efficient way to find the middle element of a list as it requires only a single traversal, resulting in a time complexity of O(n), where n is the number of elements in the list.
#include<stdio.h> 
#include<stdlib.h> 

/* Link list node */
struct Node 
{ 
	int data; 
	struct Node* next; 
}; 

/* Function to get the middle of the linked list*/
void printMiddle(struct Node *head) 
{ 
	struct Node *slow_ptr = head; 
	struct Node *fast_ptr = head; 

	if (head!=NULL) 
	{ 
		while (fast_ptr != NULL && fast_ptr->next != NULL) 
		{ 
			fast_ptr = fast_ptr->next->next; 
			slow_ptr = slow_ptr->next; 
		} 
		printf("The middle element is [%d]\n\n", slow_ptr->data); 
	} 
} 

void push(struct Node** head_ref, int new_data) 
{ 
	/* allocate node */
	struct Node* new_node = 
		(struct Node*) malloc(sizeof(struct Node)); 

	/* put in the data */
	new_node->data = new_data; 

	/* link the old list off the new node */
	new_node->next = (*head_ref); 

	/* move the head to point to the new node */
	(*head_ref) = new_node; 
} 

// A utility function to print a given linked list 
void printList(struct Node *ptr) 
{ 
	while (ptr != NULL) 
	{ 
		printf("%d->", ptr->data); 
		ptr = ptr->next; 
	} 
	printf("NULL\n"); 
} 

/* Drier program to test above function*/
int main() 
{ 
	/* Start with the empty list */
	struct Node* head = NULL; 
	int i; 

	for (i=5; i>0; i--) 
	{ 
		push(&head, i); 
		printList(head); 
		printMiddle(head); 
	} 

	return 0; 
} 

LANGUAGE:

DARK MODE: