To find middle element in linked list. Count the all nodes and divided by 2. After that add 1 then get the middle of element in linked list.
See the following code:-
public class Node {
int data;
Node next = null;
public Node(int data) {
this.data = data;
}
}
/**
* Time Complexity O(n+n/2)
*/
public Node getMiddleNode() {
Node current = head;
int middle = getMiddleIndex();
while(current != null) {
if(middle == 1) {
return current;
}
middle--;
current = current.next;
}
return null;
}
private int getMiddleIndex() {
int totalNodes = getNodesCount();
int middle = totalNodes/2;
middle = middle+1;
return middle;
}
public int getNodesCount() {
return count;
}
In Test class type the following code:-
Node middleNode = linkedList.getMiddleNode();
System.out.println("\nMiddle Node of LinkedList:- "+ middleNode.data);
Output:-
Print LinkedList Data:-
10 40 5 50 20 30
Middle Node of LinkedList:- 50