Search code examples
clinked-listaverageinsertion-sort

Calculate the sum, avg and nodes of a linked list in c


I have this linked list c program right here. It lets the user enter as many numbers as possible until 0 is entered. The list is then displayed and sorted numerically from smallest to biggest....

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int data;
    struct node *ptr;
} node;

node * insert(node *head, int num)
{
    node *temp = malloc(sizeof(node));
    temp->data = num;

    if (head == NULL || head->data > num)
    {
        temp->ptr = head;
        head = temp;
    }
    else
    {
        node *current = head;
        while ((current->ptr != NULL) && !(num < current->ptr->data))

        {
            current = current->ptr;
        }

        temp->ptr = current->ptr;
        current->ptr = temp;
    }

    return head;
}

node * delete_if_less( node *head, int data )
{
    while ( head != NULL && head->data < data )
    {
        node *temp = head;
        head = head->ptr;
        free( temp );
    }

    if ( head != NULL )
    {
        for ( node *current = head; current->ptr != NULL; )
        {
            if ( current->ptr->data < data )
            {
                node *temp = current->ptr;
                current->ptr = current->ptr->ptr;
                free( temp );
            }
            else
            {
                current = current->ptr;
            }
        }
    }

    return head;
}

void free_list(node *head) {
    node *prev = head;
    node *cur = head;
    while(cur) {
        prev = cur;
        cur = prev->ptr;
        free(prev);
    }
}

int main(){
    int num, min;
    node *head, *p;
    head = NULL;

    do {
        printf(": ");
        scanf("%d",&num);
        if(num) {
            head = insert(head, num);
            for ( p = head; p != NULL; p = p->ptr )
            {
                printf("%d ", p->data);
            }
            printf("\n");
        }
    } while(num);

    p = head;
    printf("\n:\n");

    while(p) {
        printf("%d ", p->data);
        p = p->ptr;
    }
    free_list(head);

    return 0;
}

My next step would be 1) calculating the sum of the numbers in the list 2) calculating how many numbers are in the list and finally 3) the arithmetic average of the numbers in the list. This is how it should look like...

: 1
1 
: 2
1 2
: 3
1 2 3 
: 1
1 1 2 3
: 5
1 1 2 3 5
: 0
1 1 2 3 5

total sum: 12
elements: 5
average: 2.4

My question is how do I make and calculate the sum, average and numbers of nodes of a linked list like this??


Solution

  • Sum:

    int sum = 0;
    
    for (p = head; p; p = p->ptr)
        sum += p->data;
    
    return sum;
    

    Average:

    int sum = 0;
    int count = 0;
    
    for (p = head; p; p = p->ptr)
    {
        sum += p->data;
        count++;
    }
    
    return sum / count;