C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Sum of all Nodes in a Linked List

C Program: Sum of all Nodes in a Linked List

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure for a node

struct Node {

    int data;

    struct Node *next;

};

 

// Function to create linked list

struct Node* createList(int n) {

    struct Node *head = NULL, *temp, *newNode;

    int data, i;

 

    for (i = 1; i <= n; i++) {

        newNode = (struct Node*)malloc(sizeof(struct Node));

        if (newNode == NULL) {

            printf("Memory allocation failed!\n");

            exit(0);

        }

 

        printf("Enter data for node %d: ", i);

        scanf("%d", &data);

        newNode->data = data;

        newNode->next = NULL;

 

        if (head == NULL)

            head = newNode;

        else

            temp->next = newNode;

 

        temp = newNode;

    }

    return head;

}

 

// Function to display linked list

void displayList(struct Node *head) {

    struct Node *temp = head;

    if (head == NULL) {

        printf("\nList is empty.\n");

        return;

    }

 

    printf("\nLinked List: ");

    while (temp != NULL) {

        printf("%d -> ", temp->data);

        temp = temp->next;

    }

    printf("NULL\n");

}

 

// Function to calculate sum of all nodes

int sumOfNodes(struct Node *head) {

    int sum = 0;

    struct Node *temp = head;

 

    while (temp != NULL) {

        sum += temp->data;

        temp = temp->next;

    }

 

    return sum;

}

 

int main() {

    struct Node *head = NULL;

    int n, total;

 

    printf("Enter number of nodes: ");

    scanf("%d", &n);

 

    head = createList(n);

    displayList(head);

 

    total = sumOfNodes(head);

    printf("\nSum of all nodes = %d\n", total);

 

    return 0;

}

Output

 
OUTPUT :

Enter number of nodes: 4
Enter data for node 1: 5
Enter data for node 2: 10
Enter data for node 3: 15
Enter data for node 4: 20

Linked List: 5 -> 10 -> 15 -> 20 -> NULL

Sum of all nodes = 50

Explanation

Step

Description

1

The linked list is created dynamically using malloc().

2

Each node’s data is added to a sum variable while traversing.

3

Finally, the total sum of all nodes is displayed.