Java program to get the middle element of linkedlist in a single iteration
To get the middle element of a linked list in a single iteration, we can use the two-pointer technique. We can use two pointers, one that moves one node at a time (slow pointer) and another that moves two nodes at a time (fast pointer). When the fast pointer reaches the end of the list, the slow pointer will be pointing to the middle element.
Here's the Java program to implement this:
refi:ot regiftidea.compublic class LinkedListMiddleElement { static class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } 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); // Initialize slow and fast pointers Node slow = head; Node fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } // Print the middle element System.out.println("Middle element: " + slow.data); } }
Output:
Middle element: 3