a) create a method called sum in class Node1 that will recursively calculate the
ID: 3572686 • Letter: A
Question
a) create a method called sum in class Node1 that will recursively calculate the sum of all of the int data values from that node to the last node in the list. (HINT: using the next pointer) This method should return (NOT PRINT OUT) the sum that was calculated.
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 ( wait on this part until we cover it in class)
Explanation / Answer
a). In order to calculate the recursive sum of the data node values, we have to traverse the list from the given node 'n' till the end. The node value and next parameters are private to class Node1, we can still use them directly in the same class without the need of calling getData() or getNext() functions.The following code shows how to proceed with this:
public int sum(Node1 n)
{
if(n.next==null) return n.data;
else return n.data+sum(n.next);
}
b). public void sum(int n) throw MyException
{
if(n<=0) System.out.println("the resultant sum is 0");
else{
Node1 cur=head;
int i=1;
while(cur!=null && i<=n)
{
cur=cur.getNext(); i++;
}
// given number exceeds the list size
if(cur==null) throw new Exception();
else if(cur==n)
{
int s=cur.sum(cur);
System.out.println(s);
}
}
}
// The definition of MyException class
public class MyException extends Exception
{
public MyException() {
System.out.println("Number cannot be greater than the size of the list");
}
}
// The following example code snippet shows how to use the user defined exception in the main() while calling the respective method.
try{
calling sum(n) function of the LINKEDLIST1 class;
}
catch(MyException e){
m.printStackTrace();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.