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);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章