How to Find middle element in a linked list - The Coding Shala
Home >> Interview Prep >> Find the middle element in a linked list In this post, we will learn how to find the middle element in a linked list and will implement its solution in Java. Find a middle element in a linked list Problem Given a singly linked list of N nodes. The task is to find the middle of the linked list. Example 1: Input: LinkedList: 1->2->3->4->5 Output: 3 Explanation: Middle of linked list is 3. Example 2: Input: LinkedList: 2->4->6->7->5->1 Output: 7 Explanation: Middle of linked list is 7. Find a middle element in a linked list Java Solution Approach 1 You can find the total length of the linked list then traverse again from starting and return the middle element. A better approach is to take two pointers one is a slow pointer, move by one step, and one fast pointer, move by two steps. At the time the fast pointer reaches the end slow is at the middle node. Java Program: /* No...