/* Kelly & Pohl Exercise 12.13, p. 426 */ /* */ /* Lone Leth Thomsen, 11. April 2003 */ #include <stdio.h> #include <stdlib.h> int count_r(LINK l){ if (l == NULL) return 0; else return(1+ count_r(l->next )); }; int count_i(LINK l){ int i = 0; while (l != NULL){ i++; l = l->next ; }; return i; };
![]() | int count_r(LINK l){ if (l == NULL) return 0; else return(1+ count_r(l->next )); }; |
is a recursive definition inspired by the count example on p. 411. The function count_r recursively counts the number of elements in a linked list.If the list is empty, 0 is returned, else 1 is added to the result of calling the count_r function recursively on the tail of the list. |
![]() | int count_i(LINK l){ int i = 0; while (l != NULL){ i++; l = l->next ; }; return i; }; |
is an iterative version of the count function, called count_i. A variable i is set to 0 (the counter). Then as long as there are elements in the list, 1 is added to i. Finally i is returned when the end of the list is reached. |