Suppose you have the following Node and LinkedList classes p

Suppose you have the following Node and LinkedList classes:

public class LinkedList {

private class Node {

public int item;

public Node next;

// constructor: you provide next

public Node(int newItem, Node newNext) {

item = newItem;

next = newNext;

}

// constructor: next is set to null

// (simply calls the other constructor)

public Node(int newItem) {

this(newItem, null);

}

// The usual accessors and mutators

public int getItem() {

return item;

}

public void setItem(int newItem) {

item = newItem;

}

public Node getNext() {

return next;

}

public void setNext(Node newNext) {

next = newNext;

}

} // end class Node

// Returning to class LinkedList

private Node top;

public LinkedList() {

top = null;

}

// More operations go here ...

} // end class LinkedList

QUESTION:

(b) Write a recursive void method sum that replaces each element x in the list by the

sum of x and all elements that appear after x in the list. For example, if the list

is

3 - 5 - 7 - 9 - 2

after calling sum, the list should be

26 - 23 - 18 - 11 - 2

Your method can assume no overow would occur from calling sum. You may

write a helper recursive method if necessary.

Solution

public class LinkedListSum {

   public static void main(String args[]) {

       LinkedList ll = new LinkedList();

       replaceNodeBySum(ll.getTop());

   }

   public static void replaceNodeBySum(Node node) {

       if (node.getNext() != null) {

           int sum = node.getItem() + node.getNext().getItem();

           node = node.getNext();

           node.setItem(sum);

           replaceNodeBySum(node);

       }

   }

}

Suppose you have the following Node and LinkedList classes: public class LinkedList { private class Node { public int item; public Node next; // constructor: yo
Suppose you have the following Node and LinkedList classes: public class LinkedList { private class Node { public int item; public Node next; // constructor: yo

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site