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 1->2->3->4->5 then output should be 3. If there are even nodes, then there would be two middle nodes, we need to print second middle element. For example, if given linked list is 1->2->3->4->5->6 then output should be 4.
/* Link list node */
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;
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);