Java Program to Get the middle element of LinkedList in a single iteration

To understand this example, make sure you first visit the following tutorials,

Example 1: Get the middle element of LinkedList in a single search

Output

LinkedList: 1 2 3 
Middle Element: 2

In the above example, we have implemented the linked list data structure in Java. We then find the middle element of the linked list in a single loop. Notice the code,

    while (ptr1.next != null) {

      // increase the ptr1 by 2 and ptr2 by 1
      // if ptr1 points to last element
      // ptr2 will points to middle element
      ptr1 = ptr1.next;
      if(ptr1.next !=null) {
        ptr1 = ptr1.next;
        ptr2 = ptr2.next;
      }
    }

Here, we have two variables ptr1 and ptr2. We use these variables to iterate through the linked list.

In each iteration, the ptr1 will access the two nodes and the ptr2 will access the single node of the linked list.

Now, when the ptr1 reaches the end of the linked list, the ptr2 will be in the middle. In this way, we are able to get the middle of linked list in a single iteration.


Example 2: Get the middle element of LinkedList using the LinkedList class

Output

LinkedList: [Cat, Dog, Horse]
Middle Element: Dog

In the above example, we have used the LinkedList class to implement the linked list data structure. Notice the expression,

animals.get(animals.size()/2)
  • size()/2 - returns the position of middle element
  • get() - returns the element at the middle position