Sum of the nodes of a Singly Linked List in C Program


A singly linked list is a data structure in which an element has two parts one is the value and other is the link to the next element. So to find the sum of all elements of the singly linked list, we have to navigate to each node of the linked list and add the element's value to a sum variable.

For example

Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5
sum = 2 + 27 + 32 + 1 + 5 = 67.

This can be done by using two methods :

Method 1 - Using a loop that loops over all the values of the linked list and finds the sum.

The loop runs till the end of the linked list i.e. when the pointer of an element points to null, this loop will run and find the sum of values of each element.

Example

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** nodeH, int nodeval) {
   struct Node* new_node = new Node;
   new_node->data = nodeval;
   new_node->next = (*nodeH);
   (*nodeH) = new_node;
}
int main() {
   struct Node* head = NULL;
   int sum = 0;
   push(&head, 95);
   push(&head, 60);
   push(&head, 87);
   push(&head, 6);
   push(&head, 12);
   struct Node* ptr = head;
   while (ptr != NULL) {
      sum += ptr->data;
      ptr = ptr->next;
   }
   cout << "Sum of nodes = "<< sum;
   return 0;
}

Output

Sum of nodes = 260

Method 2 - Using a recursive function that calls itself until the linked list has elements. The recursive function calls itself again and again. The call to the recursive function sends the next node values as a parameter along with the sum address location.

Example

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
   struct Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
void nodesum(struct Node* head, int* sum) {
   if (!head)
      return;
   nodesum(head->next, sum);
   *sum = *sum + head->data;
}
int main() {
   struct Node* head = NULL;
   int sum= 0;
   push(&head, 95);
   push(&head, 60);
   push(&head, 87);
   push(&head, 6);
   push(&head, 12);
   nodesum(head,&sum);
   cout << "Sum of nodes = "<<sum;
   return 0;
}

Output

Sum of nodes = 260

Updated on: 09-Aug-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements