c语言基础 05

《c程序设计语言》第6章结构,以“0,0”作为整个的起点

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define HASHSIZE 101

struct nlist {
	struct nlist *next;
	char *name;
	char *defn;
};

static struct nlist *hashtab[HASHSIZE];
struct nlish *prev;

char *strdup2(char *s);
unsigned hash(char *s);
struct nlist *lookup(char *s);
struct nlist *last(void);
struct nlist *install(char *name, char *value);

void main(){
	struct nlist *p;
	struct nlist *np;

	np = (struct nlist *)malloc(sizeof(*np));
	np->name = "0";
	np->defn = "0";
	hashtab[hash("0")] = np;

	install("a","aa");
	install("b","bb");
	install("c","bb");

	p = lookup("b");
	printf("%s\n", p->defn);

	install("b","cc");
	
	p = lookup("b");
	printf("%s\n", p->defn);
	
	p = lookup("c");
	printf("%s\n", p->defn);
}

char *strdup2(char *s){
	char *p;
	p= (char *) malloc(strlen(s)+1);
																				if(p != NULL){
		strcpy(p,s);
	}
	return p;
}

unsigned hash(char *s){
	unsigned hashval;
	for(hashval = 0; *s != '\0'; s++){
		hashval = *s + 31*hashval;
	}
	return hashval % HASHSIZE;
}

struct nlist *lookup(char *s){
	return hashtab[hash(s)];
}

struct nlist *last(){
	struct nlist *p;
	struct nlist *n;

	p = lookup("0");
	for(n = p; p == NULL; p = p->next){
		n = p;
	}
	return n;
}

struct nlist *install(char *name, char *value){
	struct nlist *np;
	struct nlist *p;
	unsigned hashval;

	if((np = lookup(name)) != NULL){
		free((void *)np->defn);
		if((np->defn = strdup2(value)) == NULL){
			return NULL;
		}
	} else {
		np = (struct nlist *)malloc(sizeof(*np));
		np->name = strdup2(name);
		np->defn = strdup2(value);
		hashtab[hash(name)] = np;

		p = last();
		p->next = np;
	}

	return np;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值