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

public class Node1 { //sum class public int sum(Node1 n) { if(n.next==null) retu

ID: 3573494 • Letter: P

Question

public class Node1 {

//sum class

       public int sum(Node1 n)

       {

       if(n.next==null) return n.data;

       else return n.data+sum(n.next);

       }



b) IN CLASS LINKEDLIST1, create a method called sum that will take an int, n, as a parameter. It will call method sum (of class Node) on the nth node in the list. (the head is node 1, the node after head is 2, etc.) And then print out to a file the sum that was calculated. If the parameter passed is negative or zero, then the sum should be zero. If n is greater than the number of nodes in the list, then throw an appropriate exception

Explanation / Answer

First of all, your code requires a small fix. There is a bug in findNode method. Please intialize prev to null instead of Node1 prev=head;

Note : The output will be written to a file called 'output.txt'. If you want a specifc name or location please provide it in the below method in place of "output.txt".

After fixing the above bug, please use the following methods as requested in the question. Paste them in the LinkedList1 class

    public void sum(int index) {
       if (index > this.size()) {
           throw new IndexOutOfBoundsException("The given index value = " +
                   index + "" + " is greater than the size of the linkelist");
       }

       int totalSum = 0;
      
       if (index > 0) {
           /* Find the nth Node
           * */
           Node1 current = head;
           for (int i = 1; i < index; i++) {
               current = current.getNext();
           }
          
           /* Find out the sum of the sub-list
           * using the sum method in Node1 Class
           * */
           totalSum = current.sum(current);
       }
      
       try {
           /* Open file, write the sum and close the file
           * Please provide the output file name with appropriate location, if required
           * */
           BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("output.txt"));
           bufferedWriter.write(String.valueOf(totalSum));
           bufferedWriter.close();
          
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
  
   /*
   * Returns the size of the linked list
   * */
   public int size(){
       int size = 0;
       Node1 cur = head;
       while (cur != null) {
           cur = cur.getNext();
           size++;
       }
       return size;
   }