Question

We have written the following Node class: class Node { // instance variables private 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
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Explanation::

  • Code in JAVA is given below
  • Please read comments for better understanding of the code
  • Output is given at the end of the code

Code in JAVA::

List.java Code:

public class List {
   private Node head;
  
   public List(Node newNode) {
       this.head = newNode;
   }
  
   public int sum() {
       /**
       *    An integer variable named total is declared and initialized to 0
       * We will store all the node values into it as summation and at the end return it
       * */
       int total = 0;
      
       /**
       * We iterate through nodes using while loop until current head is not null
       * */
       while(this.head!=null) {
           total = total + this.head.getValue();
           this.head = this.head.getNext();
       }
       return total;
   }
}

Test.java Code:

public class Test {

   public static void main(String[] args) {
       // TODO Auto-generated method stub
       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());

   }

}

NOTE : Node.java code is present in question itself :)

OUTPUT:

6

Please provide the feedback!!

Thank You!!

Add a comment
Know the answer?
Add Answer to:
We have written the following Node class: class Node { // instance variables private int value;...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Need help completing my instance method for deleteFront() as specified below To the class IntegerLinkedList, add...

    Need help completing my instance method for deleteFront() as specified below To the class IntegerLinkedList, add an instance method deleteFront such that … Method deleteFront has no input. Method deleteFront returns … an empty Optional instance if the list is empty an Optional instance whose value is the integer that was deleted from the front of the list, otherwise Hints https://docs.oracle.com/javase/10/docs/api/java/util/Optional.html import java.util.Optional; public class IntegerLinkedList { private IntegerNode head ; private int numberOfItems ; public int getNumberOfItems() { return...

  • C++ program: Convert the classes to template classes #include <iostream> #include <string> using namespace std; class Node { private: int data; Node* next; public: Node(int...

    C++ program: Convert the classes to template classes #include <iostream> #include <string> using namespace std; class Node { private: int data; Node* next; public: Node(int data) { this->data=data; this->next = 0; } int getData(){return data;} Node* getNext(){return next;} void setNext(Node* next){this->next=next;} }; class LinkedList { private: Node* head = 0; public: int isEmpty() {return head == 0;} void print() { Node* currNode = head; while(currNode!=0) { cout << currNode->getData() << endl; currNode = currNode->getNext(); } } void append(int data) {...

  • public class myLinkedList<E extends Comparable<E>>{       private Node<E> head = null;                    private Node<E>...

    public class myLinkedList<E extends Comparable<E>>{       private Node<E> head = null;                    private Node<E> tail = null;                       public myLinkedList() {        head = null;       } public void concatenateList (myLinkedList<E> M) {//attach another linkedList refered by M to the end of this linkedList       }          public int searchElement (E targetElement){//test if a target element can be found on the list, return the occurrences of the target element         ...

  • We have written the following Class1 class: class Class1 implements SecretInterface { // instance variable private...

    We have written the following Class1 class: class Class1 implements SecretInterface { // instance variable private int x = 0; // constructor public Class1(int x) { this.x = x; } // instance methods public double myMethod1(double x, double y) { return x - y; } public void myMethod2(int x) { System.out.println(x); } public String myMethod3(String x) { return "hi " + x; } } We have also written the following Class2 class: class Class2 implements SecretInterface { // instance variable...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int....

    Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int. There is also an attribute of the class, points, which does not have a corresponding instance variable. Also note the constructor and methods of the class and what they do. TournamentAdmin class code: public class RankAdmin {    /**     * Constructor for objects of class...

  • // Node.h #ifndef NODE_H #define NODE_H class Node { private: int m_entry; Node *m_next; public: Node();...

    // Node.h #ifndef NODE_H #define NODE_H class Node { private: int m_entry; Node *m_next; public: Node(); Node(int entry); int getEntry() const; void setEntry(int entry); Node *getNext(); void setNext(Node *next); }; #endif // Node.cpp #include "Node.h" Node::Node() { m_entry = 0; m_next = nullptr; } Node::Node(int entry) { m_entry = entry; } int Node::getEntry() const { return m_entry; } void Node::setEntry(int entry) { m_entry = entry; } Node *Node::getNext() { return m_next; } void Node::setNext(Node *next) { m_next = next; }...

  • CSC311: For a while now we have been discussing reference-based data structures and we have seen...

    CSC311: For a while now we have been discussing reference-based data structures and we have seen reference-based implementations of the List, Stack, and Queue ADT. For this program, you will write a reference-based implementation of the Dictionary ADT as follows: a. A Dictionary ADT is an (abstract) data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection, promptly. b. Operations associated with this data type allow: a. the...

  • Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the...

    Implement the following in java. 1. An insertAtBeginning(Node newNode) function, that inserts a node at the beginning(root) of the linked list. 2. A removeFromBeginning() function, that removes the node from the beginning of the linked list and assigns the next element as the new beginning(root). 3. A traverse function, that iterates the list and prints the elements in the linked list. For the insertAtBeginning(Node newNode) function: 1. Check if the root is null. If it is, just assign the new...

  • Java Write the function void insertAtTail (int v). Don’t add any class variables to the List...

    Java Write the function void insertAtTail (int v). Don’t add any class variables to the List class. Here are the class definitions of Node and List that implement a linked list. class Node {private Node next; private int key; Node (Node nxt, int keyValue);//constructor Node getNext(); int getKey(); void putNext(Node nxt);} class List {//assume the class does not use a dummy Node private Node head; List ();//constructor boolean exists (int ky);//returns true if v is in the list void insertAtHead(int...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT