Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "dictionary.h"
  4.  
  5. #define LENGTH 45
  6.  
  7. // A Trie node
  8.  
  9. // Function that returns a new Trie node
  10. struct Trie* emptyTrieNode()
  11. {
  12.     struct Trie* node = (struct Trie*)malloc(sizeof(struct Trie));
  13.     node->leaf = 0;
  14.  
  15.     for (int i = 0; i < LENGTH; i++)
  16.         node->character[i] = NULL;
  17.  
  18.     return node;
  19. }
  20.  
  21. // Iterative function to insert a string in Trie
  22. void addWord(struct Trie *dictionaryTrie, char* str)
  23. {
  24.     // start from root node
  25.     struct Trie* currentNode = dictionaryTrie;
  26.     while (*str)
  27.     {
  28.         // create a new node if path doesn't exists
  29.         if (currentNode->character[*str - 'a'] == NULL)
  30.             currentNode->character[*str - 'a'] = emptyTrieNode();
  31.  
  32.         // go to next node
  33.         currentNode = currentNode->character[*str - 'a'];
  34.  
  35.         // move to next character
  36.         str++;
  37.     }
  38.  
  39.     // mark currentNodeent node as leaf
  40.     currentNode->leaf = 1;
  41. }
  42.  
  43. // Iterative function to check a string in Trie. It returns 1
  44. // if the string is found in the Trie, else it returns 0
  45. bool check(struct Trie* dictionaryTrie, char* str)
  46. {
  47.     // return 0 if Trie is empty
  48.     if (dictionaryTrie == NULL)
  49.         return false;
  50.  
  51.     struct Trie* currentNode = dictionaryTrie;
  52.     while (*str)
  53.     {
  54.         // go to next node
  55.         currentNode = currentNode->character[*str - 'a'];
  56.  
  57.         // if string is invalid (reached end of path in Trie)
  58.         if (currentNode == NULL)
  59.             return false;
  60.  
  61.         // move to next character
  62.         str++;
  63.     }
  64.  
  65.     // if currentNodeent node is a leaf and we have reached the
  66.     // end of the string, return 1
  67.     return currentNode->leaf;
  68. }
  69.  
  70. void trieFree()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement