Find the middle element of linked list in C

Data structures and algorithm questions are important part of any programming job interview, whether Java interview, C, C++ interview or any other programming language. Since data structures are core programming concept, it’s mandatory for all programmers, to know basic data structures like stack, linked list, queue, array, tree, and graph.

One of the most popular questions from data structures and algorithm mostly asked during the interview. Since many programmers know that, in order to find length of linked list we need to first traverse through linked list till we find last node, which is pointing to null. Then in second pass we can find middle element by traversing only half of length.

In order to find middle element of linked list in one pass, you need to maintain two pointers, one increment at each node while other increments after two nodes at a time. By having this arrangement, when first pointer reaches end, second pointer will point to middle element of linked list. See the following C program.

For example, if given linked list is 10->20->30->40->50 then output should be 30. If there are even nodes, then there would be two middle nodes, we need to print second middle element.

```#include <stdio.h>
#include <stdlib.h>

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

/* function to insert a node at the front */void push(struct Node **head_ref, int new_data)
{
// create and a allocate a new node
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

// insert in the data in node
new_node->data = new_data;

// Make next of new node as head

// move the head to point to the new node
}

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

{
//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 (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);
}
}

int main()
{
// declare an empty list

// Create a new linked list 10->20->30->40->50 */
`The middle element is [30]`