How to find the middle element of the Linked List in Java. – IT Blog
IT Blog
Boris IT Expert

How to find the middle element of the Linked List in Java.

Boris~October 30, 2020 /Linked List

There is a straightforward way to find the middle element of the linked list java. Since it is one of the common questions on any technical interview, it is good to know the elegant solution. It will work just if you have implemented the linked list with the constructor and model class’s help. If you don’t know how to do that, this article explains the implementation in all details.

The main steps to find the middle element of the linked list Java.

To find the middle element, we will use the technique of “temporary variables.” We will follow the steps:

  1. We will set both variables to the head of the Linked List. As a result, the moving process of variables will start from the beginning of the list.
  2. We have to launch the “while” loop to work until the second variable comes to the end of the list.
  3. The main trick here is that the first variable will move +1 item on each iteration. Yet the second variable will move +2 items on each iteration. For instance, if we have 5 items on the list. After two iterations, the first variable will be on 3, but the second will be on 5. As a result, the middle of the list is 3.

Implementation scheme.

find middle element of the linked list java

Code example:

 private void findMiddleOfTheList() {
        //You need to create linked list first
        creatingLinkedList();

       //Two flags indicators
        ListNode slow = head;
        ListNode fast = head;

       //Moving until second flag face the end of the list
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        Log.d("linkedList", "middle is " + slow.data);
    }

In this article, you figured out the easiest way how to find the middle element in the linked list java.

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!