The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 6.05 on page 145
Write a function undef that will remove a name and definition from the table maintained by lookup and install .
Solutions by Paul Griffiths and Gregory Pietsch
int undef(char * name) { struct nlist * np1, * np2; if ((np1 = lookup(name)) == NULL) /* name not found */ return 1; for ( np1 = np2 = hashtab[hash(name)]; np1 != NULL; np2 = np1, np1 = np1->next ) { if ( strcmp(name, np1->name) == 0 ) { /* name found */ /* Remove node from list */ if ( np1 == np2 ) hashtab[hash(name)] = np1->next; else np2->next = np1->next; /* Free memory */ free(np1->name); free(np1->defn); free(np1); return 0; } } return 1; /* name not found */ }
Gregory Pietsch's solution
void undef(char *s) { struct nlist *np1, *np2; unsigned hashval = hash(s); for (np1 = hashtab[hashval], np2 = NULL; np1 != NULL; np2 = np1, np1 = np1->next) if (strcmp(s, np1->name) == 0) { /* found a match */ free(np1->name); free(np1->defn); if (np2 == NULL) /* at the beginning? */ hashtab[hashval] = np1->next; else /* in the middle or at the end? */ np2->next = np1->next; free(np1); return; } }










