哈希表的基本操作(平方探测法,C语言)

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct HashTable{
    int tableSize;
    struct HashBody *body;
};
struct HashBody{
    int data;
    int state;
};
int nextPrime(int num){
    num++;
    int i;
    while(1){
        int q=sqrt(num);
        for(i=2;i<=q;i++){
            if(num%i==0){
                break;
            }
        }
        if(i>q){
            return num;
        }
        num++;
    }
}
struct HashTable *createTable(int size){
    struct HashTable *H;
    H=(struct HashTable *)malloc(sizeof(struct HashTable));
    H->tableSize=nextPrime(size);
    H->body=(struct HashBody *)malloc(sizeof(struct HashBody)*H->tableSize);
    for(int i=0;i<H->tableSize;i++){
        H->body[i].state=0;
    }
    return H;
}
int Hash(int num,int size){
    return num%size;
}
int Find(struct HashTable *H,int num){
    int pos,Newpos;
    int shift=0;
    pos=Hash(num,H->tableSize);
    Newpos=pos;
    while(H->body[Newpos].state!=0&&H->body[Newpos].data!=num){
        shift++;
        Newpos=pos+shift*shift;
        Newpos=Newpos%H->tableSize;
    }
    return Newpos;
}
void Insert(struct HashTable *H,int num){
    int pos;
    pos=Find(H,num);
    if(H->body[pos].state!=1){
        H->body[pos].state=1;
        H->body[pos].data=num;
    }
}
void Delete(struct HashTable *H,int num){
    int pos;
    pos=Find(H,num);
    if(H->body[pos].state==0){
        printf("there is not this num.\n");
    }else if(H->body[pos].state==1){
        H->body[pos].state=2;
        printf("%d delete success.\n",num);
    }else{
        printf("This num had been deleted.\n");
    }
}
void show(struct HashTable *H){
    printf("此时哈希表:");
    for(int i=0;i<H->tableSize;i++){
        if(H->body[i].state==1){
            printf("%3d",H->body[i].data);
        }else{
            printf(" # ");
        }
    }
}
int main(){
    struct HashTable *H;
    int n;
    n=7;
    H=createTable(n);
    for(int i=0;i<6;i++){
        Insert(H,i+10);
    }
    Insert(H,21);
    show(H);
    printf("\n");
    Delete(H,10);
    Delete(H,21);
    show(H);
    printf("\n再次插入21\n");
    Insert(H,21);
    show(H);
    return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值