完了 写了主函数 又执行不了help
程序代码:
/* *哈希表 开放定址法 */ #include<stdio.h> #include<stdlib.h> #define MinTableSize 10 typedef int ElemType; enum KindOfEntry{Legitimate,Empty,Deleted}; typedef struct HashEntry { ElemType element; enum KindOfEntry info; }Cell; /* Cell *TheCells will be an array of */ /* HashEntry cells, allocated later */ typedef struct HashTbl { int TableSize; Cell *TheCells; }*HashTable; typedef int Index; typedef Index Position; /* Return next prime; assume N >= 10 */ int NextPrime(int N) { int i; if(N%2==0) N++; for(;;N+=2) { for(i=3;i*i<=N;i+=2) if(N%i==0) return 0; return N; } } /*Hash function for ints*/ Index Hash(ElemType Key,int TableSize) { return Key%TableSize; } HashTable InitializeTable(int TableSize) { HashTable H; int i; if(TableSize<MinTableSize) { printf("Table size too small"); return NULL; } /*Allocate table*/ H=(HashTable)malloc(sizeof(struct HashTbl)); if(NULL==H) printf("Out of space!!!\n"); H->TableSize=NextPrime(TableSize); /*Allocate array of cells*/ H->TheCells=(Cell *)malloc(sizeof(Cell)*H->TableSize); if(NULL==H->TheCells) { printf("Out of space!!!\n"); free(H); } for(i=0;i<H->TableSize;i++) { H->TheCells[i].info=Empty; H->TheCells[i].element=0; } return H; } Position Find(ElemType Key,HashTable H) { Position CurrentPos; int CollisionNum; CollisionNum=0; CurrentPos=Hash(Key,H->TableSize); while( H->TheCells[ CurrentPos ].info != Empty && H->TheCells[ CurrentPos ].element != Key )/* Probably need strcmp!! */ { CurrentPos+=2*++CollisionNum-1; if(CurrentPos>=H->TableSize) CurrentPos-=H->TableSize; } return CurrentPos; } void Insert(ElemType Key,HashTable H) { Position Pos; Pos=Find(Key,H); if(H->TheCells[Pos].info!=Legitimate) { H->TheCells[Pos].info=Legitimate;/*Ok to insert here*/ H->TheCells[Pos].element=Key;/*Probably need strcpy*/ } } HashTable ReHash(HashTable H) { int i,OldSize; Cell *OldCells; OldCells=H->TheCells; OldSize=H->TableSize; /*Get a new empty table*/ H=InitializeTable(2*OldSize); /*Scan through old table reinserting into new*/ for(i=0;i<OldSize;i++) if(OldCells[i].info==Legitimate) Insert(OldCells[i].element,H); free(OldCells); return H; } void traverseHash(HashTable H,int len) { int i; printf("哈希地址0~%d\n",len-1); for(i=0;i<len;i++) { if(H->TheCells[i].info=Legitimate)//有数据 printf("address=%d value=%d\n",i,H->TheCells[i].element); } } void DestroyTable(HashTable H) { free(H->TheCells); free(H); } int main() { HashTable H; int array[]={19,14,23,01,68,20,84,27,55,11,10,79}; int len=sizeof(array)/sizeof(array[0]); int i; // ElemType k; H=InitializeTable(len); for(i=0;i<len;i++) { Insert(array[i],H); } traverseHash(H,len); printf("\n\n"); return 0; }