Skip to content

Instantly share code, notes, and snippets.

@elazarl
Created January 21, 2012 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elazarl/1654484 to your computer and use it in GitHub Desktop.
Save elazarl/1654484 to your computer and use it in GitHub Desktop.
A simple and minimal C implementation of trie
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
// weird exercise from a friend
// need to Implement this struct
typedef struct attrib_t {
struct attrib_t* bytes[256];
const char *data;
} att;
// need to Implement this function
const char *attrib_get(att **a,const char *attrib)
{
if (*a == NULL) {
fprintf(stderr,"Get on %s from null map\n",attrib);
exit(-1);
}
if (*attrib == '\0') return (*a)->data;
return attrib_get(&((*a)->bytes[(int)*attrib]),attrib+1);
}
void attrib_init(att **a) {
*a = malloc(sizeof(**a));
memset(*a,0,sizeof(**a));
}
// need to Implement this function
void attrib_set(att **a,const char *attrib,const char *value)
{
if (*a == NULL) attrib_init(a);
if (*attrib == '\0') (*a)->data = value;
else attrib_set(&((*a)->bytes[(int)*attrib]),attrib+1,value);
}
// need to Implement this function
void attrib_free(att **a)
{
int i;
if (a == NULL || *a == NULL) return;
for (i=0;i<256;i++) attrib_free(&((*a)->bytes[i]));
free(*a);
}
int main()
{
att *a =NULL;
attrib_set(&a,"user","jhon");
attrib_set(&a,"mail","jhonSmith@gmail.com");
attrib_set(&a,"user","Smith");
printf("user = %s\nmail = %s\n" , attrib_get(&a,"user") , attrib_get(&a,"mail"));
attrib_free(&a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment