/* * definition of functions in sorted-int-list.h * * implemented using recursion (for fun?) */ #include "sorted-int-list.h" static sorted_int_list_node_t * insert_helper( sorted_int_list_node_t * lst, sorted_int_list_node_t * newnode) { if (lst == NULL) { return newnode; } else if (newnode->data < lst->data) { newnode->next = lst; return newnode; } else { lst->next = insert_helper(lst->next, newnode); return lst; } } /* * insert n into list and return updated list */ sorted_int_list_node_t * sorted_int_list_insert( sorted_int_list_node_t * lst, int n) { sorted_int_list_node_t * newnode = malloc(sizeof *newnode); if (newnode == NULL) { puts("could not get memory"); exit(1); } newnode->data = n; newnode->next = NULL; return insert_helper(lst, newnode); } /* * count occurrences of n in list */ int sorted_int_list_count(sorted_int_list_node_t * lst, int n) { if (lst == NULL) { return 0; } else if (n < lst->data) { return 0; } else if (n == lst->data) { return 1 + sorted_int_list_count(lst->next, n); } else { return sorted_int_list_count(lst->next, n); } } /* * remove all occurrences of n from list and return updated list */ sorted_int_list_node_t * sorted_int_list_remove( sorted_int_list_node_t * lst, int n) { if (lst == NULL) { return NULL; } else if (n < lst->data) { return lst; } else if (n == lst->data) { sorted_int_list_node_t * newlist = sorted_int_list_remove(lst->next, n); free(lst); return newlist; } else { lst->next = sorted_int_list_remove(lst->next, n); return lst; } } /* * remove all nodes from list and return NULL */ sorted_int_list_node_t * sorted_int_list_remove_all( sorted_int_list_node_t * lst) { if (lst != NULL) { sorted_int_list_remove_all(lst->next); free(lst); } return NULL; } /* * print all elements of lst to output stream f using format fmt * ("fmt" is the kind of string expected by fprintf, e.g., "%d " or "%d\n") * * the FILE * parameter lets the caller decide whether to print * to stdout or a file (already open) or what * the fmt parameter lets the caller decide whether to print all on * one line or each on a separate line or what */ void sorted_int_list_print(sorted_int_list_node_t * lst, FILE * f, char * fmt) { if (lst != NULL) { /* print this item */ fprintf(f, fmt, lst->data); /* print rest */ sorted_int_list_print(lst->next , f, fmt); } }