哈希表的实现(分离链表法,带头节点,C语言)

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
struct Node{
    int data;
    struct Node *next;
};
struct HashTable{
    struct Node **body;
    int tableSize;
};
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 Node **)malloc(sizeof(struct Node *)*H->tableSize);
    for(int i=0;i<H->tableSize;i++){
        H->body[i]=(struct Node *)malloc(sizeof(struct Node));
        H->body[i]->next=NULL;
    }
    return H;
}
int Hash(int num,int size){
    return num%size;
}
void Insert(struct HashTable *H,int num){
    int pos;
    pos=Hash(num,H->tableSize);
    struct Node *p,*q;
    p=H->body[pos];
    while(p->next!=NULL){
        if(p->next->data==num){
            return;
        }
        p=p->next;
    }
    p=H->body[pos];
    q=(struct Node *)malloc(sizeof(struct Node));
    q->data=num;
    q->next=p->next;
    p->next=q;
}
void show(struct HashTable *H){
    for(int i=0;i<H->tableSize;i++){
        struct Node *p;
        p=H->body[i]->next;
        printf("第%d条链:",i);
        while(p!=NULL){
            printf("%3d",p->data);
            p=p->next;
        }
        printf("\n");
    }
}
void Delete(struct HashTable *H,int num){
    int pos;
    pos=Hash(num,H->tableSize);
    struct Node *p,*q;
    p=H->body[pos];
    while(p->next!=NULL&&p->next->data!=num){
        p=p->next;
    }
    if(p->next==NULL){
        printf("There is not this num.\n");
    }else{
        q=p->next;
        p->next=q->next;
        free(q);
        printf("delete %d successfully.\n",num);
    }
}
int main(){
    struct HashTable *H;
    H=createTable(7);
    for(int i=0;i<7;i++){
        Insert(H,i+10);
        Insert(H,i+20);
        Insert(H,i+30);
    }
    printf("原哈希表:\n");
    show(H);
    printf("\n");
    Delete(H,23);
    Delete(H,36);
    printf("\n删除节点后的哈希表:\n");
    show(H);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值