C语言数据结构(六):哈希表

一、线性探测插入算法

/* 线性开放定址法 */
#include "stdlib.h"
#include "stdio.h"
#include "stdbool.h"
#include "string.h"

#define MAX_CHAR 10
#define TABLE_SIZE 13
typedef struct {
    char key[MAX_CHAR];
} Element;

Element g_hashTable[TABLE_SIZE];

void InitTable(Element *ht)
{
    for (int i = 0; i < TABLE_SIZE; i++) {
        for (int j = 0; j < MAX_CHAR; j++) {
            ht[i].key[j] = '\0';
        }
    }
}

int Transform(char *key)
{
    int number = 0;
    while (*key) {
        number += *key++;
    }
    return number;
}

int Hash(char *key)
{
    return (Transform(key) % TABLE_SIZE);
}

void LinearInsert(Element item, Element *ht)
{
    int hashValue = Hash(item.key);
    int i = hashValue;
    while (strlen(ht[i].key)) {
        // if (!strcmp(ht[i].key, item.key)) {
        //     fprintf(stderr, "Duplicated entry!\n");
        //     exit(1);
        // }
        i = (i + 1) % TABLE_SIZE;
        if (i == hashValue) {
            fprintf(stderr, "The table is full!\n");
            exit(1);
        }
    }
    ht[i] = item;
}

void VisitHashTable(Element *ht)
{
    for (int i = 0; i < TABLE_SIZE; i++) {
        int length = strlen(ht[i].key);
        for (int j = 0; j < length; j++) {
            printf("%c", ht[i].key[j]);
        }
        printf("|\n");
    }
}

void main(void)
{
    InitTable(g_hashTable);
    Element *item = (Element*)malloc(sizeof(Element));
    for (int i = 0; i < MAX_CHAR - 1; i++) {
        item->key[i] = i + 'a';
    }
    item->key[MAX_CHAR - 1] = '\0';
    LinearInsert(*item, &g_hashTable[0]);
    LinearInsert(*item, &g_hashTable[0]);
    LinearInsert(*item, &g_hashTable[0]);
    Element item2;
    for (int i = 0; i < MAX_CHAR - 2; i++) {
        item2.key[i] = i + '!';
    }
    LinearInsert(item2, &g_hashTable[0]);
    LinearInsert(item2, &g_hashTable[0]);
    LinearInsert(item2, &g_hashTable[0]);
    VisitHashTable(g_hashTable);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值