0

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);
   }
}
  • Your contents of `for loop` is wrong. you should assign the `nextItem` to the `firstItem.nextItem`. You will have to add more logic to work for `n>2` – Jitin Kodian Jan 28 '20 at 07:16

1 Answers1

1

Of course you can implement a LinkedList using nested classes. There are many ways to do it. Here you have an example: LinkedList example

But the problem you have is the variable firstItem never change. You assing the value here:firstItem = new Item((1%2!= 0), Math.sqrt(1), null);
and then you loop another variable Item nextItem = firstItem.nextItem; that is always null.

Remove the argument nextItem of constructor if you alaways set it to null.