Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of the nodes of a Singly Linked List in C Program
A singly linked list is a data structure where each node contains two parts: the data value and a pointer to the next node. To find the sum of all elements in a singly linked list, we traverse each node and add its 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
Syntax
struct Node {
int data;
struct Node* next;
};
// Iterative approach
int sumIterative(struct Node* head);
// Recursive approach
int sumRecursive(struct Node* head);
Method 1: Using Iterative Approach
This method uses a loop that traverses through all nodes of the linked list. The loop continues until it reaches the end (when the pointer becomes NULL) and accumulates the sum −
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head, int value) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = value;
new_node->next = *head;
*head = new_node;
}
int sumIterative(struct Node* head) {
int sum = 0;
struct Node* current = head;
while (current != NULL) {
sum += current->data;
current = current->next;
}
return sum;
}
int main() {
struct Node* head = NULL;
push(&head, 5);
push(&head, 1);
push(&head, 32);
push(&head, 27);
push(&head, 2);
int result = sumIterative(head);
printf("Sum of nodes = %d<br>", result);
return 0;
}
Sum of nodes = 67
Method 2: Using Recursive Approach
This method uses a recursive function that calls itself until it reaches the end of the linked list. Each recursive call processes one node and adds its value to the sum −
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head, int value) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = value;
new_node->next = *head;
*head = new_node;
}
int sumRecursive(struct Node* head) {
if (head == NULL) {
return 0;
}
return head->data + sumRecursive(head->next);
}
int main() {
struct Node* head = NULL;
push(&head, 5);
push(&head, 1);
push(&head, 32);
push(&head, 27);
push(&head, 2);
int result = sumRecursive(head);
printf("Sum of nodes = %d<br>", result);
return 0;
}
Sum of nodes = 67
Comparison
| Method | Time Complexity | Space Complexity | Pros | Cons |
|---|---|---|---|---|
| Iterative | O(n) | O(1) | No recursion overhead | Requires explicit loop |
| Recursive | O(n) | O(n) | Clean, elegant code | Stack space overhead |
Conclusion
Both iterative and recursive approaches effectively calculate the sum of linked list nodes with O(n) time complexity. The iterative method is more memory-efficient, while the recursive approach offers cleaner code structure.
