0

I would really appreciate help with Pset5 load. I initially wanted to implement a hashtable into my code but after hours of looking I couldn't find a good hashtable from the internet that I wanted to use and nothing free online would help me make my own. I've decided to make a trie but I'm not sure how the code will work. I am pretty comfortable with the idea of a trie and how it's used, but I don't know how to make one. I've rewatched all of the lectures and I've researched online but I'm still lost.

Here is my code so far:

// Define a trie
{
typedef struct node{
    bool is_word;
    struct node *children[27];
} node;
//create a root
node *root;
//open dictionary
FILE *dict = fopen(dictionary, "r");
//make sure dictionary opens
if (dict== NULL)
{
    fprintf(stderr, "Could not open %s.\n", infile);
    return false;
}
//allocate memory for root
root = malloc(sizeof(node));
}

Without giving me too much code, what are the next steps I should take? Do any of you know good sites for me to learn and practice making tries? I would love any help at all. Thanks!

0

Your structure looks fine i put it in dictionaryh.

I ran into some issues with memory leaks on this pset. I kept trying to find a solution using malloc but ended up having to go with calloc instead. (this sets all unused nodes to null)

    //malloc first node of trie list and set pointer
root = calloc(1, sizeof(node));
node *cursor = root;

its useful to set a new pointer when allocating the memory so that the original stays at root.

Basically you then want to cycle over each letter of each word and check if it exists in the cursor child and if not calloc again in that node. Something like:

            //if node doesnt exist create node
        if (cursor->children[i] == NULL)
        {
            cursor->children[i] = (node *) calloc(1, sizeof(node));
        }
        cursor = cursor->children[i];

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .