
- #include "stdio.h"
- #include "stdlib.h"
-
- typedef struct{
- int* elem; //数据元素存储基址,动态分配数组
- int count; //当前数据元素个数
- }HashTable;
-
- int m=0; //散列表表长,全局变量
-
-
- //HASHSIZE 定义散列表长为数组的长度
- typedef enum { //或者不要typedef,将Status放在前面,调用的函数前面加enum
- OK=1,SUCCESS=1,UNSUCCESS=0,HASHSIZE=12,NULLKEY=-32768
- }Status;
-
-
- Status InitHashTable(HashTable *H){ //初始化散列表
- int i;
- m=HASHSIZE;
- H->count=m;
- H->elem=(int *)malloc(m*sizeof(int));
- for(i=0;i<m;i++)
- H->elem[i]=NULLKEY;
- return OK;
- }
-
-
- int Hash(int key){ //散列函数 key相当于qq账号
- return key%m; //除留余数法 返回钥匙
- }
-
- void InsertHash(HashTable* H,int key){ //插入关键字进散列表
- int addr=Hash(key); //求散列地址
- printf("The subscript of the inserted array position:%d\n",addr);
- while(H->elem[addr]!=NULLKEY) //如果不为空,则冲突
- addr=(addr+1)%m; //开发定址法的线性探测
- H->elem[addr]=key; //直到有空位后插入关键字
- }
-
- Status SearchHash(HashTable H,int key,int* addr){ //插入关键字进散列表
- *addr=Hash(key); //求散列地址
- while(H.elem[*addr]!=key){ //如果不为空,则冲突
- *addr=(*addr+1)%m; //开发定址法的线性探测
- if(H.elem[*addr]==NULLKEY||*addr==Hash(key)){
- //如果循环回到原点
- //则说明关键字不存在
- return UNSUCCESS;
- }
- }
- return SUCCESS;
- }
-
-
- int main(){
- int i=0;
- HashTable H;
- InitHashTable(&H);
- while(i<HASHSIZE){
- InsertHash(&H,i); //插入12个数
- i++;
- }
- int key=0;
- int addr; //返回下标的作用
- while(key<HASHSIZE){
- if(SearchHash(H,key,&addr)==SUCCESS){ //搜索到了这个数的位置
- printf("Print the position of this number:%d\n",addr);
- } else{
- printf("UNSUCCESS\n");
- }
- key++;
- }
- }
-