5.3 Append
How do we append an item at the end of a list?
- Base case: the list is empty. In this case, setting the first value of the list automatically adds an item.
- Recursive step: the list is not empty. We cannot append just after the first value. We call the subroutine again
to append to the end of the rest of the list.
The code is as follows:
1void List_append(
struct List
*pList,
const char v)
2{ 3 if (List_isempty(pList))
4 { 5 List_setfirstvalue(pList,v);
6 } 7 else 8 { 9 List_append(List_getrest(pList), v);
10 } 11}
Here, line 3 checks to see if the list itself is empty. If so, then we only need to set the first value on line
5.
Otherwise, we take the rest of the list, and use the same function to append to the end of the rest.