Finding the Middle Node

Procedure to find the middle node of a singly linked list.

First Method : Finding Length & Then Middle Element

  • In the first scan of the linked list, find the length of linked list.

  • Find the ceiling value of length/2.

  • Traverse to the node having that index.

int findMid(struct node *ptr) {

    int len = 0;
    // Finding the length of linked list
    while (ptr != NULL) {
        len++;
        ptr = ptr -> next;
    }
    // Find the middle position
    int mid = ceil(len/2);
    // Resetting ptr to head
    ptr  = head;
    // Return the middle element
    for (int i = 0; i < mid; i++) {
        ptr = ptr -> next;
    }
    return ptr -> data;

}

Second Method : Using Two Pointers

  • Take two pointers with initial value as the head address.

  • Move pointer 2 two times in each iteration while it is not NULL.

  • If pointer 2 is not NULL, move pointer 1 once.

Contributed by Nitin Ranganath

Last updated

Was this helpful?