准备把最近写的一些代码一一贴出来,也算是总结吧。只能怪大学时候写的代码很少,所以读研疯狂写代码,把数据结构里面的所有东西都实现了一遍,包括图论中里面的算法。
//hash table 的线性探测法,进行溢出处理
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX_CHAR 10 // 字符串的最大大小
#define TABLE_SIZE 13 //hash table的大小
typedef struct Hash
{
char key[MAX_CHAR];
//other fields
}element;
element hash_table[TABLE_SIZE];
void InitHashTable(element ht[])
{
int i;
for( i=0 ; i<TABLE_SIZE ;i++)
ht[i].key[0]='\0';
}
int Transform(char * key)
{
int number=0;
while(*key)
{
number+=*key;
key++;
}
return number;
}
int hash(char *key)
{
return (Transform(key) % TABLE_SIZE );
}
void LinearInsert(element item ,element ht[])
{
int hash_value=hash( item.key);
int i=hash_value;
while( ht[i].key[0]!='\0' ) //该散列桶里已有填充
{
if(strcmp(item.key ,ht[i].key )==0)//桶里该标识符已存在
{
fprintf(stderr,"the identifier %s exists\n",item.key);
return;
}
i=(i+1)%TABLE_SIZE;
if(i==hash_value)
{
fprintf(stderr,"the hash table is full\n");
return;
}
}
ht[i]=item;
}
int main()
{
InitHashTable(hash_table);
element identifier[20];
strcpy(identifier[0].key,"for");
strcpy(identifier[1].key,"do");
strcpy(identifier[2].key,"while");
strcpy(identifier[3].key,"if");
strcpy(identifier[4].key,"else");
strcpy(identifier[5].key,"function");
int i;
for(i=0;i<6;i++)
LinearInsert( identifier[i] ,hash_table);
for(i=0;i<TABLE_SIZE;i++)
printf("%d. %s\n", i, hash_table[i].key);
LinearInsert( identifier[1] ,hash_table);
strcpy(identifier[7].key,"int");
strcpy(identifier[8].key,"double");
strcpy(identifier[9].key,"float");
strcpy(identifier[10].key,"extern");
strcpy(identifier[11].key,"char *");
strcpy(identifier[12].key,"auto");
strcpy(identifier[13].key,"continue");
strcpy(identifier[14].key,"break");
strcpy(identifier[15].key,"static");
for(i=7;i<=15;i++)
LinearInsert( identifier[i] ,hash_table);
for(i=0;i<TABLE_SIZE;i++)
printf("%d. %s\n", i, hash_table[i].key);
return 1;
}