Java Program to Get the Middle Element of LinkedList

Java Program to Get the middle element of LinkedList

What is LinkedList in Java ?

A linked list is a linear data structure in which each element (called a node) stores a reference to the next element in the list. Linked lists are dynamic data structures, which means that their size can change during the execution of a program. In contrast, arrays have a fixed size, which means that you need to specify the size of the array when you create it and you cannot change it later.

Steps to Get the Middle Element of LinkedList :

Pseudo Code for the above algorithm :

public static ListNode getMiddleElement(ListNode head) {
    ListNode slow = head;
    ListNode fast = head;

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

    return slow;
}

Example : 

Run
import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        // create a LinkedList with some elements
        LinkedList< Integer> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        // find the middle element of the LinkedList
        int middleIndex = list.size() / 2;
        int currentIndex = 0;
        Integer middleElement = null;
        for (Integer element : list) {
            if (currentIndex == middleIndex) {
                middleElement = element;
                break;
            }
            currentIndex++;
        }

        // print the middle element
        System.out.println("Middle element: " + middleElement);
    }

}

Output :

Middle element: 3

Example : 

Run
import java.util.LinkedList;

public class Main {

    public static void main(String[] args) {
        // create a LinkedList with some elements
        LinkedList< Integer> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        // find the middle element of the LinkedList
        int middleIndex = list.size() / 2;
        Integer middleElement = list.get(middleIndex);

        // print the middle element
        System.out.println("Middle element: " + middleElement);
    }

}

Output :

Middle element: 3

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription