Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Assume the the below function (secondToLastValue()) is within a class that has N

ID: 3593882 • Letter: A

Question

Assume the the below function (secondToLastValue()) is within a class that has Node already defined. As it is already setup below, I need to complete it without passing any parameters to the function. Can you help??

   static class Node {

       public Node (double item, Node next) { this.item = item; this.next = next; }

       public double item;

       public Node next;

   }

   Node first;

   // return the second-to-last value in the list,

   // Precondition: the list has at least 2 values

   // you can write this iteratively or recursively, but you should only have one loop or recursive helper

   // you may not call any other method (e.g. size)

   // Here are some list examples:

   // [0,1,2,5,5,5,5,5,8,9].secondToLastValue() == 8

   // [0,1].secondToLastValue() == 0

   public double secondToLastValue ( ) {

       //TODO 4: fix this

   }

Thanks!!

Explanation / Answer

Please find my implementation.

static class Node {

       public Node (double item, Node next) { this.item = item; this.next = next; }

       public double item;

       public Node next;

   }

   Node first;

   // return the second-to-last value in the list,

   // Precondition: the list has at least 2 values

   // you can write this iteratively or recursively, but you should only have one loop or recursive helper

   // you may not call any other method (e.g. size)

   // Here are some list examples:

   // [0,1,2,5,5,5,5,5,8,9].secondToLastValue() == 8

   // [0,1].secondToLastValue() == 0

   public double secondToLastValue ( ) {

       //TODO 4: fix this

      

       // list is empty or having only one element

       if(first == null || first.next == null)

           return -999;

      

       Node last = first.next;

       Node secondLast = first;

      

       while(last.next != null) {

           secondLast = last;

           last = last.next;

       }

      

       return secondLast.item;

   }