Skip to content

Instantly share code, notes, and snippets.

@devyn
Created November 13, 2012 06:56
Show Gist options
  • Save devyn/4064396 to your computer and use it in GitHub Desktop.
Save devyn/4064396 to your computer and use it in GitHub Desktop.
#include "trie.h"
void trie_create (trie_t **trie, char edgeName, trie_t *previousSibling, trie_t *parent)
{
*trie = calloc(1, sizeof(struct trie));
(*trie)->edgeName = edgeName;
if (previousSibling == NULL) {
if (parent != NULL) parent->firstChild = *trie;
} else {
previousSibling->nextSibling = *trie;
}
}
void trie_destroy (trie_t **trie)
{
while ((*trie)->firstChild != NULL)
trie_destroy(&(*trie)->firstChild);
trie_t *next = (*trie)->nextSibling;
free(*trie);
*trie = next;
}
int trie_search (trie_t *trie, char *name, trie_t **dest)
{
while (*name != '\0') {
if (trie == NULL) {
return 0;
} else if (trie->edgeName == *name) {
if (*++name != '\0')
trie = trie->firstChild;
} else {
trie = trie->nextSibling;
}
}
*dest = trie;
return 1;
}
#ifndef TRIE_H
#define TRIE_H
#include <stdlib.h>
typedef struct trie {
char edgeName;
struct trie *nextSibling;
struct trie *firstChild;
void *value;
} trie_t;
void trie_create (trie_t **trie, char edgeName, trie_t *previousSibling, trie_t *parent);
void trie_destroy (trie_t **trie);
int trie_search (trie_t *trie, char *name, trie_t **dest);
void trie_insert (trie_t **trie, char *name, void *value);
void trie_delete (trie_t **trie, char *name);
#endif
#include <stdio.h>
#include "trie.h"
int main(int argc, char **argv)
{
trie_t *first, *im1, *im2, *im3, *last1, *last2;
printf ("Creating hello\n");
trie_create (&first, 'h', NULL, NULL);
trie_create (&im1, 'e', NULL, first);
trie_create (&im2, 'l', NULL, im1);
trie_create (&im3, 'l', NULL, im2);
trie_create (&last1, 'o', NULL, im3);
last1->value = "This is the result for 'hello'.";
printf ("Creating hi\n");
trie_create (&last2, 'i', im1, first);
last2->value = "This is the result for 'hi'.";
trie_t *dest;
if (trie_search (first, "hello", &dest)) {
printf ("hello => \"%s\"\n", dest->value);
} else {
fprintf (stderr, "hello: NOT FOUND\n");
}
if (trie_search (first, "hi", &dest)) {
printf ("hi => \"%s\"\n", dest->value);
} else {
fprintf (stderr, "hi: NOT FOUND\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment