OAIP_Mirror/lab26/Sources/DictHash.c
2024-12-06 15:17:07 +04:00

87 lines
1.8 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Ðåàëèçàöèÿ ñëîâàðÿ íà õýøå
//
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdlib.h>
#include "Dict.h"
#define MAX_HASH 13267
struct Node {
char* word;
struct Node* next;
};
// Ìàññèâ ñïèñêîâ
struct Node* first[MAX_HASH];
// Âû÷èñëåíèå õýøà äëÿ ñòðîêè word
int hash(char* word) {
unsigned long hash_value = 0;
int i = 0;
while (word[i] != '\0') {
hash_value = 31 * hash_value + ((unsigned)(word[i]));
i++;
}
return hash_value % MAX_HASH;
}
/* INSERT äîáàâëÿåò ýëåìåíò â ìíîæåñòâî.
Ìíîæåñòâî ñîäåðæèò òîëüêî óíèêàëüíûå ýëåìåíòû.
Ïðè ïîâòîðíîì äîáàâëåíèè ýëåìåíòà â ìíîæåñòâî, ìíîæåñòâî íå èçìåíÿåòñÿ.
Íåò çàùèòû îò äâîéíîãî âêëþ÷åíèÿ */
void Insert(char* word) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
int hash_value = hash(word);
newNode->next = first[hash_value];
newNode->word = (char*)calloc(strlen(word) + 1, sizeof(char));
strcpy(newNode->word, word);
first[hash_value] = newNode;
}
/* MEMBER ñîîáùàåò, ÿâëÿåòñÿ ëè óêàçàííûé ýëåìåíò ÷ëåíîì äàííîãî ìíîæåñòâà èëè íåò. */
int Member(char* word) {
int hash_value = hash(word);
struct Node* ptr = first[hash_value];
while (ptr != NULL) {
if (strcmp(ptr->word, word) == 0) {
return 1;
}
ptr = ptr->next;
}
return 0;
}
/* CREATE - ñîçäàåò ñëîâàðü.
Âûçûâàåòñÿ ïåðåä íà÷àëîì èñïîëüçîâàíèÿ ñëîâàðÿ. */
void Create() {
for (int i = 0; i < MAX_HASH; i++)
first[i] = NULL;
}
/* DESTROY - óíè÷òîæàåò ñëîâàðü.
Âûçûâàåòñÿ ïîñëå îêîí÷àíèÿ èñïîëüçîâàíèÿ ñëîâàðÿ. */
void Destroy() {
for (int i = 0; i < MAX_HASH; i++) {
while (first[i] != NULL) {
struct Node* delNode = first[i];
first[i] = first[i]->next;
free(delNode->word);
free(delNode);
}
}
}