[算法] trie树实现

小写字母的字典树

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 1000
#define LEN 100

char END[LEN] = "0";

struct node{
    struct node* next[26];    
    int id;
    int end;    
};

int count;
char book[MAXN][LEN];
struct node root;

int isin(struct node *root, char *tmp) {
    char head;
    if(tmp[0] == '\0') {
        if(root->end == 1) {
            return 1;
        }
        else {
            return 0;     
        }
    } 
    head = *(char *)tmp - 'a';
    if(root->next[head] == NULL) {
        return 0;  
    }
    return isin(root->next[head], tmp + 1);
}


void insert(struct node *root, char *tmp)
{
    struct node *t;
    if(tmp[0] == '\0') {
        root->end = 1;
        root->id = count;
        return;
    }
    t = (struct node *)malloc(sizeof(struct node));
    t->id = -1;
    t->end = 0;
    memset(t->next, 0, sizeof(t->next));
    root->next[*(char *)tmp - 'a'] = t;
    insert(t, tmp + 1);
    return;
}

int main() {
    
    /* init */
    char tmp[LEN];
    int i;
    count = 0;
    memset(book, 0, sizeof(book));
    root.id = -1;
    root.end = 0;
    memset(root.next, 0, sizeof(root.next));

    while(1) {
        scanf("%s", tmp);     
        if(strcmp(tmp, END) == 0) {
            break;     
        }
        if(isin(&root, tmp) == 1) {
            printf("already in\n");     
        }
        else {
            strcpy(book[count], tmp);
            insert(&root, tmp);
            count ++;
        }
    }
    printf("now we have %d words:\n", count);
    for(i = 0; i < count; i++) {
        printf("%s\n", book[i]);    
    }
    return 0;    
}

  

posted @ 2014-01-15 19:13  ~嘉言懿行~~我是煲仔饭~~  阅读(221)  评论(0编辑  收藏  举报