C Program to find middle element in the linked list

Finding middle element of the linked list using C

C Program to find middle element of the linked list. To learn how to find middle element of singly linked list in one pass you may need to adjust two pointers, one increment at each node while other pointer increments after two nodes at a time by having such arrangements when the first pointer reaches end then second pointer will point to middle element of the linked list.If there are even number of nodes then there will be possibility of two middle nodes in which we need to print second middle element of the node.
For Example:- If the given linked list is,
Input:-1->2->3->4->5->6, then
Output:- 4

To find middle element of the linked list using C

Implementation of finding middle element of the linked list:-

  • First take two pointers first node and second node
  • Initially first node increment by one pass and second node increment after two nodes passes.
  • Make the link of first node to point to link of q and free q.
  • Then move first node to its end.
  • After that move second node to middle of the list
  • Return second node element.
C Program to find middle element of the linked list

Constructing node Structure in the following box:-

struct node
{
int data;
struct node *next;
};

C Program to find middle element of the linked list:-

#include <stdio.h> 
#include <stdlib.h>  
struct Node   //Link list node 
{
    int data;
    struct Node* next;
};
void insert(struct Node **head_ref, int new_data)     // function to insert values
{
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 
    new_node->data = new_data;  
    new_node->next = (*head_ref);  
    (*head_ref) = new_node;  
} 
void print_Middle(struct Node *head)     //Function found the middle element in the linked list
{
    struct Node *first_ptr = head;
    struct Node *second_ptr = head;
 
    if (head!=NULL)
    {
        //the only logic is to traverse the linked list with two pointers
        //one at normal speed and other twice the speed of first
        /*when the fast pointer reaches to the end, slow pointer will be in 
        the middle of the linted list*/
        while (second_ptr != NULL && second_ptr->next != NULL)
        {
            second_ptr = second_ptr->next->next;
            first_ptr = first_ptr->next;
        }
        printf("The middle element in the linked list is:- %d", first_ptr->data);
    }
}
int main() 
{ 
    struct Node* head = NULL; 
    insert(&head, 80); 
    insert(&head, 15); 
    insert(&head, 31); 
    insert(&head, 44);
    insert(&head, 92); 
    print_Middle(head);  //print output
    return 0; 
}
Output:-
The middle element in the linked list is:- 31

To study more about Linked List Click below:-