In this blog post, we will learn how to write a Java program to find the middle element of a linked list.
When working with linked lists, one of the common tasks is to find the middle element. This task might sound simple with arrays, but since linked lists are sequential and don't provide direct access to their indices, we have to come up with efficient strategies to find the middle element.
How the Algorithm Works
Two Pointers: Similar to detecting a cycle, we use two pointers – slow and fast.
Movement: The slow pointer moves one step at a time, whereas the fast pointer moves two steps.
Middle Element: By the time the fast pointer reaches the end of the list, the slow pointer will be in the middle of the list.
Let's dive into the Java program that demonstrates this approach.
Java Program to Find the Middle Element of a Linked List
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class MiddleElementFinder {
public static int findMiddle(Node head) {
if (head == null) {
return -1; // Return -1 or throw an exception based on use-case
}
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; // Move one step
fast = fast.next.next; // Move two steps
}
return slow.data; // Middle element's data
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
System.out.println("Middle Element: " + findMiddle(head)); // Should return 3
head.next.next.next.next.next = new Node(6);
System.out.println("Middle Element: " + findMiddle(head)); // Should return 4
}
}
Output:
Middle Element: 3
Middle Element: 4
Comments
Post a Comment
Leave Comment