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

哈希表的基本 *** 作(平方探测法,C语言),第1张

哈希表的基本 *** 作(平方探测法,C语言
#include
#include
#include
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;itableSize;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;itableSize;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再次插入21n");
    Insert(H,21);
    show(H);
    return 0;
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5579368.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存