所以我在这个项目上工作只是为了刷新哈希表和一些 C 库..
我已经使用文件 i/o 实现了通用哈希函数和基本表所需的一切。但是当我试图考虑如何调整表大小时,我陷入了困境。
我想知道是否最好将数据从我的表复制到一个新的..或者在第一个填充时初始化一个新的哈希表..
我的困惑主要在于如何有效地将一个哈希表的值复制到一个新的哈希表文件中,以及如何处理前一个文件的无用内存分配
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int currSize = 0;
int tableSize = 25;
typedef struct mydata_tag{
int used;
/* 0 - empty 1- used */
int key;
char name[25];
char ailment[30];
char insurance[30];
char social[10];
} mydata;
int setInfo(mydata * data)
{
printf("What is the client's ailment?");
scanf("%s", data->ailment);
printf("What is the client's insurance provider?");
scanf("%s", data->insurance);
printf("What is the client's Social Security Number?");
scanf("%s", data->social);
}
int hashKey(char * name){
int key, len, i;
key = 0;
len = strlen(name);
for(i = 0; i < len; i++)
{
key += name[i] * 10;
}
key %= 19;
key %= 7;
return key;
}
void init_table(char *filename, int size)
{
if(!filename || size < 1)
{
exit(1);
}
currSize++;
FILE * fp;
mydata data;
int i;
memset(&data, 0, sizeof(data));
fp = fopen(filename, "w+"); //create file with write capabilities
for(i = 0; i < size; i++)//initialize table
{
fwrite(&data, sizeof(mydata), i, fp);
}
}
void insert_data(double key, char *name, char *filename)
{
if(!name || !filename)
{
exit(1);
}
FILE * fp;
mydata data, slot;
int pos;
pos = key;
data.used = 1;
data.key = key;
strcpy(data.name, name);
setInfo(&data);
fp = fopen(filename, "r+");
while(1)
{
fseek(fp, pos*sizeof(mydata), SEEK_SET);
fread(&slot, sizeof(mydata), 1, fp);
if(slot.used != 1)
{
break;
}
printf("COLLISION!\n");
pos++;
pos %= 19;
pos %= 7;
}
printf("pos = %d\n", pos);
printf("key = %d\n", data.key);
fseek(fp, pos*sizeof(mydata), SEEK_SET);
fwrite(&data, sizeof(mydata), 1, fp);
fclose(fp);
}
void print_buckets(char * filename)
{
FILE * fp;
mydata data;
int i;
fp = fopen(filename, "r+");
if(fp == NULL)
{
perror("fopen: print_buckets");
exit(1);
}
for(i = 0; i < 25; i++)
{
fread(&data, sizeof(mydata), 1, fp);
if(data.used == 1){
printf("used = %d \n key = %d \n Name = %s\n Ailment: %s \n",
data.used, data.key, data.name, data.ailment);
}
}
fclose(fp);
}
int main(int argc, char** argv) {
int i, key;
init_table("myhashtable", tableSize);
while(1)
{
char choice[1];
printf("----------Menu-----------\n");
printf("------(A)dd Client-------\n");
printf("---(P)rint Client List---\n");
printf("---------(E)xit----------\n");
scanf("%s", &choice);
if(choice[0] == 'e' || choice[0] == 'E'){break;}
else if(choice[0] == 'a' || choice[0] == 'A')
{
char name[20];
printf("What is the clients name?");
scanf("%s", &name);
key = hashKey(name);
insert_data(key, name, "myhashtable");
}else if(choice[0] == 'p' || choice[0] == 'P'){
print_buckets("myhashtable");
}
}
return (EXIT_SUCCESS);
}
编辑:这是一个古老而愚蠢的问题,无视