C程序设计语言 (第二版) 练习 6-5
练习 6-5 编写函数undef,它将从由lookup和install维护的表中删除一个变量及其定义。
注意:代码在win32控制台运行,在不同的IDE环境下,有部分可能需要变更。
IDE工具:Visual Studio 2010
代码块:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>#define HASHSIZE 101struct nlist {struct nlist *next;char *name;char *defn;
};static struct nlist *hashtab[HASHSIZE];unsigned hash(char *s) {unsigned hashval;for(hashval = 0; *s != '\0'; s++){hashval = *s + 31 * hashval;}return hashval % HASHSIZE;
}char *_strdup(char *s){char *p;p = (char *) malloc(strlen(s) + 1);if (p != NULL){strcpy(p, s);}return p;
}struct nlist *lookup(char *s){struct nlist *np;for(np = hashtab[hash(s)]; np != NULL; np = np->next){if (strcmp(s, np->name) == 0){return np;}}return NULL;
}struct nlist *install(char *name, char *defn){struct nlist *np;unsigned hashval;if ((np = lookup(name)) == NULL){np = (struct nlist *) malloc(sizeof(*np));if(np == NULL || (np->name = _strdup(name)) == NULL){return NULL;}hashval = hash(name);np->next = hashtab[hashval];hashtab[hashval] = np;}else{free((void *) np->defn);}if ((np->defn = _strdup(defn)) == NULL){return NULL;}return np;
}int undef(char * name){struct nlist * np1, * np2;if ((np1 = lookup(name)) == NULL){return 1;}for(np1 = np2 = hashtab[hash(name)]; np1 != NULL; np2 = np1, np1 = np1->next){if (strcmp(name, np1->name) == 0){if(np1 == np2){hashtab[hash(name)] = np1->next;}else{np2->next = np1->next;}free(np1->name);free(np1->defn);free(np1);return 0;}}return 1;
}int main(){system("pause");return 0;
}