《数据结构》C语言——散列(哈希)表(开放地址散列方法、链表散列方法)

开放地址方法

#define Size  1001
typedef struct HTNode
{
   
    int element;
    bool Empty;//标记之前是否存储过元素(这个位置只要使用过就置 false) 
}HTNode;

typedef struct {
   
    int MaxSize;
    HTNode *ht;
} MyHashSet;

       //开放地址散列法 
MyHashSet* myHashSetCreate() {
   
    MyHashSet* Hash = (MyHashSet*)malloc(sizeof(MyHashSet));
    Hash->MaxSize = Size;
    Hash->ht = (HTNode*)malloc(sizeof(HTNode)* Hash->MaxSize);
    
    int i;
    for(i = 0;i<Hash->MaxSize;i++)
    {
   
        Hash->ht[i].element = -1;
        Hash->ht[i].Empty = true;
    }
    return Hash;
}

void myHashSetAdd(MyHashSet* obj, int key) {
   
    int i = key%obj->MaxSize;
    int j = i;
    do
    {
   
        if(obj->ht[j].element == key)
            return;
        else if(obj->ht[j].element == -1)
        {
   
            obj->ht[j].Empty = false;
            obj->ht[j].element = key;
            return;
        
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include #include typedef struct node { int data; struct node *next; }node; init_hash(node **A,int n) { int i; for(i=0;idata=0; A[i]->next=NULL; } } insert_hash(node **A,int value,int n) { int key; node *p,*q; key=value%n; if(A[key]->next!=NULL) { p=A[key]->next; while(p->next!=NULL) p=p->next; q=(node *)malloc(sizeof(node)); q->data=value; q->next=NULL; p->next=q; } else { q=(node *)malloc(sizeof(node)); q->data=value; q->next=NULL; A[key]->next=q; } } int search_hash(node **A,int value,int n) { int key; node *p; key=value%n; if(A[key]->next==NULL) return 0; else { p=A[key]->next; while(p!=NULL) { if(p->data==value) return 1; } return 0; } } delete_hash(node **A,int value,int n) { int key; node *p,*q; key=value%n; p=A[key]; q=A[key]->next; while(q->data!=value) { p=q; q=q->next; } p->next=q->next; free(q); } print_hash(node **A,int n) { int i; node *p; for(i=0;inext!=NULL) { p=A[i]->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } } } printf("\n"); } main() { int i,n,value,Case; node **A; printf("输入待排序元素个数:\n"); scanf("%d",&n); A=(node **)malloc(sizeof(node*)*n); //申请一个指针型数组A[n] init_hash(A,n);//初始化数组A printf("输入hash的值(空格键分开):\n"); for(i=0;i<n;i++) //建hash { scanf("%d",&value); insert_hash(A,value,n); } printf("请选择hash的操作\n1.查询\t2.插入\t3.删除\t4.输出\n"); scanf("%d",&Case); switch(Case) { case 1: { printf("请输入要查询的元素:"); scanf("%d",&value); printf(search_hash(A,value,n)?"Success!\n":"Failure!\n"); //查询 } case 2: { printf("请输入要插入的元素:"); scanf("%d",&value); insert_hash(A,value,n); //插入 } case 3: { printf("请输入要删除的元素:"); scanf("%d",&value); printf(search_hash(A,value,n)?"删除成功!\n":"中不存在该元素!\n"); delete_hash(A,value,n); } case 4: //输出 { printf("中元素为:\n"); print_hash(A,n); } } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值