void addToEnd(int x, List& L) { if(isEmpty(L)) { L = cons(x, emptyList); } else { addToEnd(x, L->next); } }
Since the definition of addToEnd is tail-recursive, an optimizing compiler can turn it into a loop. You can write it directly as a loop using a reference variable, which refers to another variable.
void addToEnd(int x, List& L) { List& p = L; while(!isEmpty(p)) { p = p->next; } p->next = cons(x, emptyList); }
When the loop ends, p is a variable that holds NULL. It is the 'next' variable in the last cell, or is variable L if L is NULL. It is important to use p->next instead of tail(p) since tail(p) is not a variable.