Is it possible to emulate a linked list in java by nesting a class within a class? I have tried to implement, but the summation function doesn't move passed the first class. This generates a 1 no matter what integer it is given:
public class Example {
static class Item{
boolean b;
double d;
Item nextItem;
Item (boolean b, double d, Item nextItem) {
this.b = b;
this.d = d;
this.nextItem = nextItem;
}
}
static double f(Item item) {
if(item != null)
return (item.b ? item.d : 0.0) + f(item.nextItem);
else
return 0.0;
}
static public void main(String args[]) {
int n = Integer.parseInt(args[0]);
Item firstItem = null;
firstItem = new Item((1%2!= 0), Math.sqrt(1), null);
if(n > 1){
Item nextItem = firstItem.nextItem;
for (int i = 2; i <= n; i++) {
nextItem = new Item((i%2!=0), Math.sqrt(i), null);
nextItem = nextItem.nextItem;
}
}
double s = f(firstItem);
System.out.println("sum = " + s);
}
}