hash表-使用数组加链表实现hash表

hash表-使用数组加链表实现hash表

hash.h

typedef int ElementType;
struct ListNode{
    ElementType Element;
    int val;
    struct ListNode * next;
};
typedef struct ListNode * Position;
typedef Position List;
struct HashTbl{
    int TableSize;
    List * TheLists;
};

typedef struct HashTbl * HashTable;
HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(ElementType Key,HashTable H);
void Insert(ElementType Key,HashTable H);
ElementType Retrieve(Position P);
void list_free(struct ListNode * head);
int aHash(int x);

hash.c

#include <stdio.h>
#include <stdlib.h>
#include "hash.h"

int main()
{
    HashTable H = InitializeTable(10);
    int i = 0;
    for(i=0;i<10;i++)
    {
        Insert(i*i,H);
    }
    Insert(99,H);
    Find(49,H);
    DestroyTable(H);
}

HashTable InitializeTable(int TableSize){
    HashTable H;
    int i;
    H = malloc(sizeof(struct HashTbl));
    H->TableSize = TableSize;
    H->TheLists = malloc(sizeof(List)*TableSize);
    for(i=0;i<H->TableSize;i++){
        H->TheLists[i] = mallic(sizeof(struct ListNode));
        H->TheLists[i]->next = NULL;
    }
    return H;
}

void DestroyTable(HashTable H){
    if(H==NULL)
        return;
    int tablesize = H->TableSize;
    int i = 0;
    for(i=0;i<tablesize;i++)
    {
        struct ListNode * head = H->TheLists[i];
        list_free(head);
    }
    free(H->TheLists);
    free(H);
}

void list_free(struct ListNode * head){
    if(head==NULL)
        return;
    struct ListNode * temp = head;
    while(head->next!=NULL)
    {
        temp = head->next;
        head->next = temp->next;
        free(temp);
    }
    free(head);
}

int aHash(int x){
    return x%10;
}

void Insert(ElementType Key,HashTable H){
    int p = aHash(Key);
    struct ListNode * po = H->TheLists[p];
    struct ListNode * temp = malloc(sizeof(struct ListNode));
    temp->Element = Key;
    temp->val = Key-1;
    temp->next = po->next;
    po->next = temp;
}

Position Find(ElementType Key,HashTable H){
    int p = aHash(Key);
    struct ListNode * po = H->TheLists[p];
    struct ListNode * temp = po->next;
    while(temp!=NULL){
        if(temp->Element==Key){
            printf("Key=%d, value=%d\n",Key,temp->val);
            return temp;
            break;
        }
        temp=temp->next;
     }
     return NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值