1 #include "hash.h"
2 #include <string.h>
3 #include <stdio.h>
4
5
6 static Node * _make_node(const char * word, size_t count, Node * next);
7
8 static void _add_node(Node * head, Node * newNode);
9
10 static void _delete_next_node(Node * prev);
11
12 static Node * _make_node(const char * word, size_t count, Node * next)
13 {
14
15 char * newStr = (char*)malloc(sizeof(char) * strlen(word));
16 memcpy(newStr, word, strlen(word));
17 Node * newNode = (Node *)malloc(sizeof(Node));
18 newNode->count = count;
19 newNode->word = newStr;
20 newNode->next = next;
21 return newNode;
22 }
23
24 static void _add_node(Node * head, Node * newNode)
25 {
26 newNode->next = head->next;
27 head->next = newNode;
28 }
29
30 static void _delete_next_node(Node * prev)
31 {
32 Node * delNode = prev->next;
33 prev->next = delNode->next;
34 free(delNode->word);
35 free(delNode);
36 }
37
38 void init_words(Words * words)
39 {
40 for(int i = 0; i < SIZE; i++)
41 words->head[i] = _make_node("",0,NULL);
42 }
43
44 void destroy_words(Words * words)
45 {
46 for(int i = 0; i < SIZE; i++)
47 {
48 Node * p = words->head[i];
49 while(p->next)
50 _delete_next_node(p);
51 free(p->word);
52 free(p);
53 }
54 }
55
56 size_t hash_fun(const char * word)
57 {
58 return (word[0] - 'a') % SIZE;
59 }
60
61 bool append_word(Words * words,const char * word)
62 {
63 size_t index = hash_fun(word);
64 Node * current = words->head[index]->next;
65 while(current)
66 {
67 if(!strcmp(current->word, word))
68 {
69 current->count++;
70 return false;
71 }
72 else current = current->next;
73 }
74 Node * newNode = _make_node(word,1,NULL);
75 _add_node(words->head[index], newNode);
76 words->head[index]->count++;
77 return true;
78 }
79
80 bool delete_word(Words * words, char * word)
81 {
82 size_t index = hash_fun(word);
83 Node * current = words->head[index];
84 while(current->next)
85 {
86 if(!strcmp(current->next->word, word))
87 {
88 words->head[index]->count--;
89 _delete_next_node(current);
90 return true;
91 }
92 current = current->next;
93 }
94 return false;
95 }
96
97 void print_words(Words * words)
98 {
99 for(int i = 0; i < SIZE; i++)
100 {
101 if(!words->head[i]->count)
102 continue;
103 for(Node * p = words->head[i]; p; p=p->next)
104 printf("(%s, %zu) ", p->word, p->count);
105 printf("
");
106 }
107 printf("
");
108 }