X731: Linked Chain Find Middle Node

Consider the following class definitions:

public class LinkedChain<T> {
    private Node<T> firstNode;
    private int numberOfEntries;

    public LinkedChain() {
        firstNode = null;
        numberOfEntries = 0;
    }// end default constructor


    public int getNumberOfEntries() {
        return numberOfEntries;
    }



    public void push(T newEntry) {
        // TODO Auto-generated method stub
        firstNode = new Node<T>(newEntry, firstNode);
        numberOfEntries++;
    }
}

Where Node is defined as:

public class Node<T> {
     private T data; // Entry in bag
     private Node<T> next; // Link to next node

     public Node(T dataPortion) {
         this(dataPortion, null);
     } // end constructor


     public Node(T dataPortion, Node<T> nextNode) {
         data = dataPortion;
         next = nextNode;
     } // end constructor


     public T getData() {
         if (data != null) {
             return data;
         }
         return null;
     }


     public Node getNext() {
         return next;
     }


     public void setNext(Node<T> newNext) {
         next = newNext;
     }
}

Below, write a Linked Chain method that will return reference to the middle node. If the Linked Chain has an even number of nodes the "middle node" should be closer to the back.

For example, if the linked chain looked like this:

A --> B --> C --> D

where firstNode referenced the node containing A, this method would return the node containing C

If the linked chain looked like this:

A --> B --> C --> D --> E

where firstNode referenced the node containing A, this method would return the node containing C

If there is one node, the code should return that node. If the linked chain is empty be sure to return null.

Your Answer:

Reset
Visualize

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.