#include #include "freq-list.h" #define increment_freq(n) (n)->freq++ static char *new_word(char *w) { char *tmp; if ( (tmp = (char *) malloc(strlen(w)+1)) == NULL) { fprintf(stderr, "Out of memory.\n"); exit(-1); } return strcpy(tmp, w); } static struct freq *new_node(char *word, int freq) { struct freq *n = (struct freq *) malloc(sizeof (struct freq)); if (n == NULL) { fprintf(stderr, "Out of memory.\n"); exit(-1); } n->word = word; n->freq = freq; n->next = NULL; return n; } /* This is a constant now */ /* freq_list fl_empty = NULL; */ freq_list new_freq_list() { return new_node((char *)NULL, -1); } static freq_list fl_add(char *word, int freq, freq_list fl) { struct freq *n; char *wordcopy = new_word(word); n = new_node(wordcopy, freq); n->next = fl; return n; } struct freq *fl_lookup(char *word, freq_list fl) { if ( (fl == NULL) || (strcmp(word, fl->word) == 0) ) return fl; else return fl_lookup(word, fl->next); } void fl_foreach(void (*fn)(char *, int), freq_list fl) { struct freq *tmp; for (tmp = fl; tmp != NULL; tmp = tmp->next) (*fn)(tmp->word, tmp->freq); } freq_list fl_insert(char *word, freq_list fl) { struct freq *tmp = fl_lookup(word, fl); if (tmp == NULL) return fl_add(word, 1, fl); else return increment_freq(tmp), fl; } freq_list fl_destroy(struct freq *fl) { free(fl->word); fl_destroy(fl->next); free(fl); return fl_empty; }