Write a Java Program to find middle element in LinkedList.

Below program shows how to find middle element in LinkedList.

public class FindMiddleElementTest {
 
	public static void main(String[] args) {
		LinkedList list = new LinkedList();
		for (int i = 7; i > 0; --i) {
			list.insert(i);
		}
		list.print(list);
		findMiddleElementInList(list);
	}
	
	private static int findMiddleElementInList(LinkedList list) {
		Node fastPtr = list.head;
		Node slowPtr = list.head;
		while (fastPtr.next != null && fastPtr.next.next != null) {
			fastPtr = fastPtr.next.next;
			slowPtr = slowPtr.next;
		}
		System.out.println("Middle element is " + slowPtr.data);
		return slowPtr.data;
	}
}

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.