简单的字典树

  • 实现了一个C语言写的简单字典树,节点之间跳转,用链表实现
  • 节点定义
typedef struct _tire_node
{
   struct _tire_node *word[MAX_ASCII_VALUE];
   int value;
}TireNode;
  • 插入节点
void InsertNode(TireNode *node, char * key, int value)
{
    int i = 0;
    for ( i = 0; i < strlen(key); i++)
    {
        if (node->word[key[i]] == NULL)
        {
            node->word[key[i]] = (TireNode *)malloc(sizeof(TireNode));
            nodecount++;
        }

        if (i == strlen(key) - 1)
        {
            node->word[key[i]]->value = value;
        }

        node = node->word[key[i]];
    }
}
  • 查找节点
int SearchNode(TireNode *node, char *key)
{
    int i = 0;;
    for (i = 0 ; i < strlen(key); i++)
    {
        if (node == NULL)
        {
            return 0;
        }

        if (node->word[key[i]] == NULL)
        {
            return 0;
        }
        else
        {
            if (node->word[key[i]]->value > 0)
            {
                return  node->word[key[i]]->value;
            }
            else
            {
                node = node->word[key[i]];
            }

        }
    }
}

  • 测试代码
int main()
{
    int i = 0;                            
    char *httphead[] = {                                                                                                                 
          "Uri=",          
          "Host=",         
          "Referer=",   
          "User-Agent=",
          "Pragma=",       
          "x-online-host=",
          "X-Requested-With=",
          "c_version=", 
          "X-Umeng-Sdk=",
          "Client-Agent=",
          "appname=",   
          "DPUName=",   
          "actionlocation=",
          "Cookie=",       
          "http.useragent="
     };

     TireNode *root = (TireNode *)malloc(sizeof(TireNode));
    memset(root, 0, sizeof(TireNode));

    TireNode *node = root;
    for (i = 0; i < 15; i++)
    {
        InsertNode(node, httphead[i], i +  1);
    }


    for(i = 14; i >= 0; i--)
    {
        int ret = 0;
        node = root;
        ret = SearchNode(root,httphead[i]);
        if (ret > 0)
        {
            printf("%d\n", ret);
        }
    }
    printf("nodenum is %u, size is :%u KB\n", nodecount, nodecount * sizeof(TireNode)/1024);

    return 0;

}

  • 实现的很粗糙, 单纯的字典树,节点消耗了太多了内存,不适于实际应用,后面会接着给出字典树的压缩版本,前缀树,后缀树,检索树等

你可能感兴趣的:(简单的字典树)