The C Programming Language

Chapter 6 - Structures 5

mmresult 2017. 12. 22. 10:48

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;
        }
}


 

 

'The C Programming Language' 카테고리의 다른 글

Chapter 7 - Input and Output 1  (0) 2017.12.22
Chapter 6 - Structures 6  (0) 2017.12.22
Chapter 6 - Structures 4  (0) 2017.12.22
Chapter 6 - Structures 3  (0) 2017.12.22
Chapter 6 - Structures 1  (0) 2017.12.22