the c proggramming language 替换文本源码

本文详细介绍了散列表的实现原理,包括散列函数的设计、冲突解决策略以及如何使用散列表进行查找和安装操作。通过具体代码示例,深入探讨了散列表在程序设计中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include <ctype.h> 
#include <string.h> 
#include <stdlib.h> 
#define MAXWORD 100 
#define BUFSIZE 100 
#define HASHSIZE 101 
static struct nlist *hashtab[HASHSIZE]; /* pointer table指向结构体变量的指针数组 */
struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */
};
/*散列函数 hash 在 lookup 和 install 函数中都被用到,它通过一个 for 循环进行计
算,每次循环中,它将上一次循环中计算得到的结果值经过变换(即乘以 31)后得到的新值
同字符串中当前字符的值相加(*s + 31 * hashval),然后将该结果值同数组长度执行取
模操作,其结果即是该函数的返回值。*/
/* hash: form hash value for string s */
//在散列计算时采用的是无符号算术运算,因此保证了散列值非负
unsigned hash(char *s)
{
    unsigned hashval;
    for (hashval = 0; *s != '\0'; s++)
        hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}
/* lookup: look for s in hashtab */
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; /* found */
    return NULL; /* not found */
}
struct nlist *lookup(char *);
char *strdup(char *);
/* install: put (name, defn) in hashtab */
/*install 函数借助 lookup 函数判断待加入的名字是否已经存在。如果已存在,则用新
的定义取而代之;否则,创建一个新表项。如无足够空间创建新表项,则 install 函数返回
NULL。*/
struct nlist *install(char *name, char *defn)
{
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        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 /* already there */
        free((void *)np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
        return NULL;
    return np;
}
char *strdup(char *s) /* make a duplicate of s */
{
    char *p;
    p = (char *)malloc(strlen(s) + 1); /* +1 for '\0' */
    if (p != NULL)
        strcpy(p, s);
    return p;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值