5.4 Get value of a certain position
Getting tired of only using List_isempty to terminate? Here’s a slight twist. Let us write a subroutine to return the value of
the item at “index” n. The item has an index of 0.
- Base case 1: the list is empty. There is no value to return. Use an “illegal” value to indicate the problem.
- Base case 2: the index is 0. This means we can return the first value of the list.
- Recursive step: the list is not empty, and the index is not 0. In this case, we take the rest of the list, decrease
the index by one (because the first value of the rest is the second of the current list), and all the subroutine
again.
The code is as follows;
1int List_getvalue(
struct List
*pList,
unsigned index)
2{ 3 return List_isempty(pList) ?
-1 :
4 (index == 0) ? List_getfirstvalue(pList) :
5 List_getvalue(List_getrest(pList), index
-1);
6}
Line 3 return -1 because the list is empty. If the list if not empty, then the right hand side of : is evaluated.
Line 4 returns the first value of the list because index is 0. If index is not 0, then the right hand side of : is
evaluated.
Line 5 takes the rest of the list, decrease index by one, and calls the subroutine again. Whatever this invocation returns,
the same value is returned.