🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Linked List Statistics Single Pass
Count occurrences and compute minimum, maximum, sum and average in one list traversal.
Linked List Statistics in One Pass
Here is the next pair of exercises in our free C programming course: count how many times a value appears in a linked list, and find the largest element, the smallest element, the total and the average. Beginners often write one loop per question, five loops in all. A professional answer reads the list once and keeps running results. That habit matters in embedded C programming, where data may arrive from a sensor chain or a ring of buffers and you may not get a second look at it.
In this lecture you will build a small statistics structure, fill it in a single traversal, handle the empty list honestly, and see why the sum needs a wider type than the values themselves.
What You Will Learn
- How to traverse a linked list with a
constpointer when you only read it - How to count occurrences of a value with a simple counter loop
- How to track minimum, maximum and sum in one pass
- Why the first node, not zero, must seed the minimum and maximum
- How to compute an average without integer truncation
- How to report that an empty list has no statistics instead of inventing numbers
Prerequisites
You should be able to build and walk a singly linked list and know how to return a status code from a function. If you followed the earlier lectures of this free embedded C course, you are ready.
Counting Occurrences
Counting is the simplest traversal. Start a counter at zero, visit each node, and increase the counter whenever the node’s value equals the wanted value. The function takes a const struct node * because it does not change the list, and returns a size_t because a count cannot be negative and may be as large as the number of nodes.
Minimum, Maximum, Sum and Average Together
A single loop can maintain all four numbers. The important detail is how you start. Never initialise the minimum to zero or the maximum to zero: if every value is positive the minimum would stay at zero, and if every value is negative the maximum would stay at zero. Seed both with the value of the first node, which is a real element, and then compare the rest.
| Variable | Starts as | Updated when |
|---|---|---|
| min | first node’s value | a smaller value is seen |
| max | first node’s value | a larger value is seen |
| sum | 0 | every node (added) |
| count | 0 | every node (incremented) |
| average | computed after the loop | sum divided by count, as double |
The sum is kept in a long long. Adding many int values can exceed the range of int even though each value fits, and signed overflow is undefined behaviour in C. The average is computed by converting both operands to double first. Writing sum / count with integers would silently drop the fractional part and report 5 instead of 5.429.
The Empty List Problem
What is the smallest value in an empty list? There is no answer. The function therefore returns -1 to say it could not compute statistics, and leaves the caller to decide what to print. This is better than returning a fake zero, because zero could be a legitimate minimum. Returning a status plus filling an output structure is a pattern you will see in every kernel and driver API.
The Complete Program
The list is built by pushing each value to the front, which is the quickest way to create a list. The data array is therefore stored in reverse order: 15, -2, 3, 9, 3, 7 are pushed one by one, then one extra 3 is pushed last, so the list reads 3 7 3 9 3 -2 15. That gives seven nodes with three 3s, a smallest value of -2 and a largest value of 15.
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
struct list_stats {
size_t count;
int min;
int max;
long long sum;
double average;
};
static struct node *push_front(struct node *head, int value)
{
struct node *n = malloc(sizeof *n);
if (!n) {
return head;
}
n->value = value;
n->next = head;
return n;
}
static size_t count_value(const struct node *h, int wanted)
{
size_t hits = 0;
for (; h; h = h->next) {
if (h->value == wanted) {
hits++;
}
}
return hits;
}
/* One pass over the list. Returns -1 for an empty list (no min/max exists). */
static int compute_stats(const struct node *h, struct list_stats *s)
{
if (!h) {
return -1;
}
s->count = 0;
s->sum = 0;
s->min = s->max = h->value;
for (; h; h = h->next) {
if (h->value < s->min) {
s->min = h->value;
}
if (h->value > s->max) {
s->max = h->value;
}
s->sum += h->value;
s->count++;
}
s->average = (double)s->sum / (double)s->count;
return 0;
}
static void free_list(struct node *h)
{
while (h) {
struct node *next = h->next;
free(h);
h = next;
}
}
int main(void)
{
const int data[] = {15, -2, 3, 9, 3, 7}; /* pushed in front, so list reads 7 3 9 3 -2 15 ... */
struct node *head = NULL;
struct list_stats st;
for (size_t i = 0; i < sizeof data / sizeof data[0]; i++) {
head = push_front(head, data[i]);
}
head = push_front(head, 3);
printf("occurrences of 3 : %zu\n", count_value(head, 3));
printf("occurrences of 8 : %zu\n", count_value(head, 8));
if (compute_stats(head, &st) == 0) {
printf("count : %zu\n", st.count);
printf("smallest : %d\n", st.min);
printf("largest : %d\n", st.max);
printf("sum : %lld\n", st.sum);
printf("average : %.3f\n", st.average);
}
if (compute_stats(NULL, &st) != 0) {
puts("empty list : no statistics");
}
free_list(head);
return 0;
}Build and Run
gcc -std=c11 -Wall -Wextra -o ep_liststats ep_liststats.c
./ep_liststatsoccurrences of 3 : 3
occurrences of 8 : 0
count : 7
smallest : -2
largest : 15
sum : 38
average : 5.429
empty list : no statisticsVerify by hand: the values are 3, 7, 3, 9, 3, -2 and 15. Their total is 38, the count is 7, and 38 divided by 7 is 5.428571, shown as 5.429 with three decimals. The occurrence count for 3 is three, and for 8 it is zero.
Why a Struct for the Results
The function could have returned just one number, but there are five results. Packing them in struct list_stats lets the function return all of them through one pointer, and the caller reads them by name. This is the same reason device drivers pass a configuration structure instead of ten separate arguments: the call stays readable and adding a field later does not change the function signature.
You might wonder whether the count loop should be folded into the statistics loop as well. It could, but it takes a parameter, the wanted value, that the statistics do not need. Keeping the two functions separate makes each one easy to test. Merge them only when profiling shows that the extra pass matters.
Common Mistakes and Troubleshooting
| Mistake | Effect | Fix |
|---|---|---|
| Seeding min or max with 0 | Wrong result for all-positive or all-negative lists | Seed with the first node |
| Integer division for the average | 5 instead of 5.429 | Cast to double before dividing |
Summing into an int | Possible overflow, undefined behaviour | Use long long |
| Dividing by zero on an empty list | Crash or NaN | Check for the empty list first |
| Walking with the head pointer itself | Head lost, nodes leaked | Advance a local copy |
| Forgetting to free the list | Memory leak | Call free_list() at the end |
Warning:
Do not use INT_MIN or INT_MAX as seeds unless you also handle the empty list. Seeding with the first element is simpler and cannot give a value that is not in the list.
Best Practices
- Do one traversal and keep running results instead of looping once per question.
- Use
constparameters for read-only traversals. - Use the widest sensible type for accumulators.
- Report impossible cases, such as statistics of nothing, through a return code.
- Test with an empty list, a one-node list, all-negative values and repeated values.
Performance and security notes:
A single pass is O(n) in time and O(1) in extra memory. On a real device where the list is modified by an interrupt handler, disable interrupts or take a lock during the traversal, or you may read a half-updated list.
Try It Yourself
Modify the program in three ways to cement the idea. First, change the data array so every value is negative, for example -4, -9 and -1, and confirm that the maximum is -1 rather than zero; this proves your seeding is right. Second, add a function that returns the position of the first occurrence of a value, counting from zero, or -1 when it is absent. Third, add the median by copying the values into an array and sorting it, which shows when a second pass or extra memory is genuinely needed. Each variation is short, and each one exercises a different habit that firmware reviewers look for.
Summary and Key Takeaways
- Counting is a one-variable loop; statistics are four variables in one loop.
- Seed minimum and maximum with the first element.
- Accumulate in a wide type and divide in
double. - An empty list has no minimum, so return an error code.
- A results structure keeps a multi-value function clean.
Conclusion
With one small function you have answered four exercise questions and learned a pattern that applies to sensor readings, packet sizes and queue depths. The next lecture of the free C programming course uses everything so far to maintain student records in a sorted linked list and search them by roll number.
Frequently Asked Questions
Why return -1 for an empty list?
Because no valid minimum or maximum exists. A distinct status lets the caller handle it without confusing it with real data.
Why size_t for the count?
It is the standard unsigned type for sizes and counts, so it can never be negative.
Can the average be computed without a double?
Yes, as a fixed-point value such as the sum times 1000 divided by the count, which is common on chips without floating point.
Does the order of nodes affect the result?
No. Count, minimum, maximum, sum and average do not depend on order.
What if two values are equal for the minimum?
The comparison uses strictly smaller, so the first occurrence is kept; the value is the same either way.
How do I find the position of the maximum?
Keep an index counter and store it whenever the maximum changes.
Keep Learning C for Free
Continue the free embedded C course with student records and searching a linked list.

2 Comments