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,

  1. The method returns null if the Singly LinkedList is empty;
  2. The method returns the Consider the following Singly LinkedList java codes public class Node{ private Object th node if the Singly LinkedList has n nodes, where n is an odd number;
  3. The method returns the element; private Node next; // the constructor, methods setElement(), setNext(), getElement(), getNext() 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 2

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!