X408: Linked Chain Find Node Before Value

Consider the following class definitions:

public static final class LinkedChain<T> {
    private Node<T> topNode;
    private int numberOfEntries;

    public LinkedChain() {
        this.topNode = null;
        numberOfEntries = 0;
    }// end default constructor


    public Node<T> getTopNode() {
        return topNode;
    }

    public int getNumberOfEntries() {
        return numberOfEntries;
    }

    public boolean compareNodes(Node<T> n1, Node<T> n2) {
        return n1.equals(n2);
    }

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

Where node looks like this:

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 a reference to the node before the first node in the chain that equals to a given parameter (otherwise return null) - could do this with a look ahead or runner technique. Make sure to account for edge cases!

Your Answer:

Reset
Visualize

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.