Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implements a dictionary's functionality
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <strings.h>
- #include <string.h>
- #include "dictionary.h"
- // Represents a node in a hash table
- typedef struct node
- {
- char word[LENGTH + 1];
- struct node *next;
- }
- node;
- // Number of buckets in hash table
- const unsigned int N = 26;
- // Hash table
- node *table[N];
- // Returns true if word is in dictionary else false
- bool check(const char *word)
- {
- // TODO
- node *cursor = table[hash(word)];
- while (cursor != NULL)
- {
- if (strcasecmp(word, cursor->word) == 0)
- {
- return true;
- }
- cursor = cursor ->next;
- }
- return false;
- }
- // Hashes word to a number
- unsigned int hash(const char *word)
- {
- // TODO
- int i = word[0] - 97;
- return i;
- }
- // Loads dictionary into memory, returning true if successful else false
- int count = 0;
- bool load(const char *dictionary)
- {
- // TODO
- FILE *file;
- file = fopen(dictionary, "r");
- if (file == NULL)
- {
- //printf("Error!\n");
- return false;
- }
- char* word = NULL;
- while(fscanf(file, "%s", word) != EOF)
- {
- node *n = malloc(sizeof(node));
- if (n == NULL)
- {
- return false;
- }
- strcpy(n->word, word);
- n->next = table[0]->next;
- table[0]->next = table[hash(word)]->next;
- count ++;
- }
- return true;
- }
- // Returns number of words in dictionary if loaded else 0 if not yet loaded
- unsigned int size(void)
- {
- // TODO
- return count;
- }
- // Unloads dictionary from memory, returning true if successful else false
- bool unload(void)
- {
- // TODO
- for (int i = 0; i < (N - 1); i++)
- {
- node *cursor = table[i];
- node *tmp = cursor;
- while(cursor != NULL)
- {
- cursor = cursor->next;
- free(tmp);
- tmp = cursor;
- }
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement