X729: Linked Chain Find Last

Consider the following class definitions:

x
 
1
public class LinkedChain<T> {
2
    private Node<T> firstNode;
3
    private int numberOfEntries;
4
5
    public LinkedChain() {
6
        firstNode = null;
7
        numberOfEntries = 0;
8
    }// end default constructor
9
10
11
    public int getNumberOfEntries() {
12
        return numberOfEntries;
13
    }
14
15
16
17
    public void push(T newEntry) {
18
        // TODO Auto-generated method stub
19
        firstNode = new Node<T>(newEntry, firstNode);
20
        numberOfEntries++;
21
    }
22
}

Where Node is defined as:

32
 
1
public class Node<T> {
2
     private T data; // Entry in bag
3
     private Node<T> next; // Link to next node
4
5
     public Node(T dataPortion) {
6
         this(dataPortion, null);
7
     } // end constructor
8
9
10
     public Node(T dataPortion, Node<T> nextNode) {
11
         data = dataPortion;
12
         next = nextNode;
13
     } // end constructor
14
15
16
     public T getData() {
17
         if (data != null) {
18
             return data;
19
         }
20
         return null;
21
     }
22
23
24
     public Node getNext() {
25
         return next;
26
     }
27
28
29
     public void setNext(Node<T> newNext) {
30
         next = newNext;
31
     }
32
}

Below, write a Linked Chain method that will return reference to the last node in the chain. If the linked chain is empty be sure to return null.

Your Answer:

xxxxxxxxxx
4
 
1
public Node<T> getLastNode() {
2
    
3
}
4
Reset
Visualize
Next exercise

Feedback

Your feedback will appear here when you check your answer.