C program to find the sum of elements in the linked list

PROGRAM:

#include <stdio.h>
#include <stdlib.h>
//Creating structure
struct node
{
    int data;
    struct node *link;
}*first=NULL;

//function prototypes
struct node * create(struct node *);
int sumlink(struct node *);

//main function
int main()
{
    int sum=0;
    printf("\nEnter elements to create linked list\n");
    first=create(first);
    printf("\nLinked list created!\n");
    sum=sumlink(first);
    printf("\nSum of nodes in the linked list= %d\n",sum);
    return 0;
}

//function to create linked list
struct node * create(struct node *first)
{
    struct node *new_node;
    int choice=0;

    do
    {
        new_node=(struct node *)malloc(sizeof(struct node));
        printf("\nEnter  an element\n");
        scanf("%d",&new_node->data);
        new_node->link=NULL;
        if(first==NULL)
            first=new_node;
        else
        {
            new_node->link=first;
            first=new_node;
        }
        printf("\nEnter 1 to continue, 0 to stop\n");
        scanf("%d",&choice);
    }while(choice==1);
    return first;
}

//function to find the sum of nodes in the linked list
int sumlink(struct node *first)
{
    struct node *temp;
    int sum=0;
    if(first==NULL)
        return 0;
    else if(first->link==NULL)
        return first->data;
    else
    {
        temp=first;
        while(temp!=NULL)
        {
            sum=sum+temp->data;
            temp=temp->link;
        }
        return sum;
    }
}
 

OUTPUT:

Enter elements to create linked list

Enter  an element
10

Enter 1 to continue, 0 to stop
1

Enter  an element
20

Enter 1 to continue, 0 to stop
1

Enter  an element
30

Enter 1 to continue, 0 to stop
1

Enter  an element
40

Enter 1 to continue, 0 to stop
1

Enter  an element
50

Enter 1 to continue, 0 to stop
0

Linked list created!

Sum of nodes in the linked list= 150


Popular Posts