C //练习 6-5 编写函数undef,它将从由lookup和install维护的表中删除一个变量及其定义。

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 101

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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-17 11:36:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-17 11:36:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-17 11:36:01       87 阅读
  4. Python语言-面向对象

    2024-01-17 11:36:01       96 阅读

热门阅读

  1. Redis的实现四:事件循环和计时器

    2024-01-17 11:36:01       55 阅读
  2. leetcode

    2024-01-17 11:36:01       57 阅读
  3. 3d姿态 mhformer 预测代码

    2024-01-17 11:36:01       42 阅读
  4. Python-pytest使用allure工具

    2024-01-17 11:36:01       61 阅读
  5. 智慧校园大数据平台概述

    2024-01-17 11:36:01       50 阅读
  6. 修改大型二进制库函数名的bash 脚本及其解释

    2024-01-17 11:36:01       49 阅读
  7. Docker

    2024-01-17 11:36:01       58 阅读
  8. STM32 基础知识(探索者开发板)--159讲 CAN总线

    2024-01-17 11:36:01       50 阅读
  9. 设计模式-抽象工厂模式

    2024-01-17 11:36:01       49 阅读