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

A LinkedList is a data structure in Java that consists of nodes connected through pointers.

It is a very useful data structure that allows for efficient insertion and deletion operations.

One common task when working with LinkedLists is to find the middle element.

In this tutorial, we will discuss how to get the middle element of LinkedList in a single iteration using Java.


To start, we will first create a LinkedList in Java.

We can do this by creating a new instance of the LinkedList class, and then adding elements to it using the add() method.

Here is an example:

LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

In this example, we have created a LinkedList of integers and added five elements to it.

Now, we will discuss how to get the middle element of this LinkedList in a single iteration.

To get the middle element of the LinkedList in a single iteration, we can use the fast and slow pointer method.

This method involves iterating through the LinkedList with two pointers, one moving twice as fast as the other.

When the fast pointer reaches the end of the LinkedList, the slow pointer will be pointing to the middle element.

Here is the Java code that implements this method:

public static <T> T getMiddleElement(LinkedList<T> list) {
    Iterator<T> slow = list.iterator();
    Iterator<T> fast = list.iterator();

    while (fast.hasNext() && fast.next() != null) {
        if (!fast.hasNext()) {
            return slow.next();
        }
        slow.next();
        fast.next();
    }
    return null;
}

In this code, we start by creating two iterators, one for the slow pointer and one for the fast pointer.

We then iterate through the LinkedList with the fast pointer moving twice as fast as the slow pointer.

When the fast pointer reaches the end of the LinkedList, the slow pointer will be pointing to the middle element.

We then return the middle element.

To use this method, we can simply call the getMiddleElement() method and pass in our LinkedList as an argument.

Here is an example:

LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);

Integer middleElement = getMiddleElement(list);
System.out.println("Middle Element: " + middleElement);

In this example, we call the getMiddleElement() method and pass in our LinkedList as an argument.

We then print out the middle element.


In conclusion, getting the middle element of a LinkedList in a single iteration is a common task when working with LinkedLists in Java.

The fast and slow pointer method is a simple and efficient way to accomplish this task.

By using this method, we can iterate through the LinkedList in a single iteration and find the middle element.