Write a program using Java to find the middle node of a linked list (ensure that the number of nodes of the LL is an odd number).
import java.util.LinkedList;
import java.util.Optional;
import java.util.Scanner;
public class Test {
public static Object findMiddleElementLinkedList(LinkedList linkedList) {
if (linkedList == null || linkedList.isEmpty()) {
return Optional.empty();
}
return linkedList.get( (linkedList.size() - 1) / 2);
}
public static int checking(){
int numberOfElements;
System.out.println("Enter an odd number of elements: ");
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
if ((number % 2) == 0){
System.out.println("The number of elements is not odd");
numberOfElements = checking();
}
else {
numberOfElements = number;
}
return numberOfElements;
}
public static void main(String args[]){
LinkedList<Integer> list = new LinkedList<>();
int numberOfElements = checking();
for (int i = 1; i <= numberOfElements; i++){
list.add(i);
}
System.out.println(list);
System.out.println("The middle node of a linked list - " + findMiddleElementLinkedList(list));
}
}
Comments
Leave a comment