Question
Consider the following Singly LinkedList java codes public class Node{ private Object element; private Node next; // the constructor, methods setElement(), setNext(), getElement(), getNext() are
Consider the following Singly LinkedList java codes
public class Node{
private Object element;
private Node next;
// the constructor, methods setElement(), setNext(), getElement(), getNext() are omitted
}
public class SLL {
private Node head;
// the constructor, methods setHead(), getHead(), add(), remove() are omitted
}
Write a method in class SLL to find the middle element. Specifically,
- The method returns null if the Singly LinkedList is empty;
- The method returns the th node if the Singly LinkedList has n nodes, where n is an odd number;
- The method returns the th node if the Singly LinkedList has n nodes, where n is an even number.
Please show your idea and the java code. Use comments to make your java code easy to understand.
Remark: You can only call the method getNext(). You cannot call other methods. This is to prevent the following trick: assume there is a method "miracle" in SLL which can do exactly what describes in the question. If so, then the answer would be simply public Node middle(){ return miracle(); }.
n+1 2Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started