计算c中链表的总和、平均值和节点

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

我这里有这个链表c程序。它让用户输入尽可能多的数字,直到输入 0。然后显示列表并按数字从小到大排序....

#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;
}

我的下一步是 1) 计算列表中数字的总和 2) 计算列表中有多少数字,最后 3) 列表中数字的算术平均值。它应该是这样的...

: 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

我的问题是如何制作和计算这样一个链表的总和、平均值和节点数??

总和:

int sum = 0;

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

return sum;

平均:

int sum = 0;
int count = 0;

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

return sum / count;