What exactly does this code fragment do?
#include <stdio.h>
List *makeList(int n) {
List *l, *l1 = NULL;
for (int i = 0; i < n; i++) {
l = malloc(sizeof(List));
l->val = n-i;
l->next = l1;
l1 = l;
}
return l;
}
My notes say that “Given a number n,
build a list of length n where
the ith element of the list
contains i”
But I don’t get that…
The tricky thing here is that the list is built backwards, note that each element’s value is set to
n - i, andicounts from 0 ton - 1. So, the first element will get valuen, the next one will getn - 1, and so on.This is probably done in order to save on a variable (!); otherwise it would be required to have another pointer to remember the first node, in order to have something to
return.Also, it doesn’t check the return value of
malloc(), which is always scary.For
n = 0, it will return an undefined value (the value ofl), which is really scary.