Step 3 of 6
Length and sum
Most list functions follow the same traversal pattern: start at the head, do something with each node, follow next until NULL. Only the "do something" changes.
#include <stdio.h>
#include <stddef.h>
struct Node {
int value;
struct Node *next;
};
int list_max(const struct Node *head) {
int best = head->value;
for (const struct Node *p = head->next; p != NULL; p = p->next) {
if (p->value > best) {
best = p->value;
}
}
return best;
}
int count_negative(const struct Node *head) {
int n = 0;
for (; head != NULL; head = head->next) {
if (head->value < 0) {
n++;
}
}
return n;
}
int main(void) {
struct Node c = {-4, NULL}, b = {9, &c}, a = {-1, &b};
printf("max %d, negatives %d\n", list_max(&a), count_negative(&a));
return 0;
}
max 9, negatives 2
Notes
count_negativemoves the parameterheaditself. That's fine: it's the function's own copy of the pointer, so the caller's list is unaffected.const struct Node *promises the function won't modify the nodes; traversal functions should always takeconst.list_maxreadshead->valuewithout checking, so it requires a non-empty list. A function that must handle empty lists (like counting or summing) should work naturally whenheadisNULL: the loop simply doesn't run and the result is 0.
Think about the empty list for every list function you write; it's the most common edge case in hidden tests.
Your turn: write two traversal functions:
int list_length(const struct Node *head)int list_sum(const struct Node *head)