C/C++ Arena

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

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:

Previous: Push to the front Next: Free the whole list