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.

Linked List

Linked List

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.

Output of the program is:
The middle element is [30]