Question: We have written the following Node class: class Node { // instance variables private int value; private Node next; // constructor public Node(int value) {

We have written the following Node class:

class Node { // instance variables private int value; private Node next; // constructor public Node(int value) { this.value = value; } // get the 'next' variable public Node getNext() { return this.next; } // get the 'value' variable public int getValue() { return this.value; } // set the 'next' variable public void setNext(Node next) { this.next = next; } }

TASK: Create a class called List that has the following properties:

  • It should have one private instance variable of type Node called head
  • It should have a constructor with one parameter of type Node, which sets the head instance variable to the argument
  • It should have a non-parametric public instance method called sum that returns the sum of head.value, head.next.value, head.next.next.value, etc.

EXAMPLE: If we run the following code:

Node node = new Node(1); node.setNext(new Node(2)); node.getNext().setNext(new Node(3)); List list = new List(node); System.out.println(list.sum());

We should print 1 + 2 + 3 = 6.

Sample Input:

1 2 3

Sample Output:

6

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!