I'm trying to implement linked Lists. I therefore have this first class, called List, which represents one element
package list;
/**
* Linked list with int values.
*
* The empty list is represented by a null reference.
*/
public class List {
public int value;
public List next;
/**
* Creates a new list
*
* @param value value of the head of the list
* @param next reference to rest of the list; may be null
*/
public List(int value, List next)
{
this.value = value;
this.next = next;
}
}
and the linked list class itself which contains the following method
public static int size(List list)
{
if(list==null) return 0;
else return size(list.next)+1;
}
so far everything works. But if I try
public static int size(List list)
{
if(list.next==null) return 1;
else return size(list.next)+1;
}
i get a NullPointerException... I have no Idea why this shouldn't work since list.next should a one point be a reference to the null pointer and end the recursion. Therefore size(null.next) should never be called.
I apologise for the bad english and am grateful for any help