I’m having a problem in which the method outputs null instead of returning the (n+1)th item of the list. Is there anything that I’m overlooking .
public static ListElement getItem(ListElement head, int n){
if(n == 0){
return head;
}else if(head == null){
return null;
}else{
return getItem(head.getNext(),n+1);
}
}
This code doesn’t make sense. If head is not null, it will call
getItem(head.getNext(), n+1)but eventually,headwill equalnull(andnwill never go to 0) and therefore it will return younull. Maybe you meantreturn getItem(head.getNext(), n-1).