In: Computer Science
using java
Consider the following LinkedList that is composed of 4 nodes containing 13, 7, 24, 1. Assume that the Node.value is an int, and the reference to the first value is a Node called n. Write a method that computes the sum of all the values in the nodes of a linked list. For example, your method shall return the sum of all the nodes, in this example shall return 45
Below is code for method which returns sum of all nodes in java.
public int sumOfAllNodes() {
Node cur = head;
int sum = 0;
while(cur != null)
{
sum = sum + cur.value;
cur = cur.next;
}
return sum;
}
Below is whole code.
public class Main {
static class Node {
int value;
Node next;
public Node(int a) {
value = a;
next = null;
}
}
Node head; // tail
public Main() {
head = null;
}
public void insertFirst(int a) {
Node newNode = new Node(a);
newNode.next = head;
head = newNode;
// if (tail == null) tail = newNode;
}
public int sumOfAllNodes() {
Node cur = head;
int sum = 0;
while(cur != null)
{
sum = sum + cur.value;
cur = cur.next;
}
return sum;
}
public String toString() {
if (head == null) return "The list is empty.";
StringBuilder sb = new StringBuilder();
sb.append(head.value);
Node cur = head.next;
while ( cur != null ) {
sb.append(" -> " + cur.value);
cur = cur.next;
}
return sb.toString();
}
public static void main(String[] args) {
Main list = new Main();
list.insertFirst(1);
list.insertFirst(24);
list.insertFirst(7);
list.insertFirst(13);
System.out.println(list);
int sum = list.sumOfAllNodes();
System.out.println(sum);
}
}
Output: