The ListNode class is the same as we already used for the linked implementation of stacks and queues:
class ListNode {
Object data;
ListNode next;
ListNode(Object data, ListNode next) {
this.data = data;
this.next = next;
}
}
The LinkedList class will now have two private instance
variables, a list node head, referring to the first node in the
list, and an integer size. It has a single constructor taking
no arguments:
public class LinkedList {
private ListNode head;
private int size;
public LinkedList() {
head = null;
size = 0;
}
Calling the LinkedList constructor creates an empty list
represented internally by the null reference. The size
of the empty list is of course 0.
Corresponding to these two variables are the two public methods:
public boolean isEmpty() {
return (head == null);
}
and
public int size() {
return size;
}
It is not essential to maintain a count of the size of the list, but
it is more efficient than counting the size afresh each time the
size method is called.