Answer to Question #309553 in Java | JSP | JSF for Kyle

Question #309553

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).


1
Expert's answer
2022-03-19T13:57:26-0400
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));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS