Chinaunix首页 | 论坛 | 博客
  • 博客访问: 984574
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C/C++

2013-01-11 23:34:01

Trie树基本实现代码。
练习使用。codepad.org已验证。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <memory.h>
  4. #define CSIZE 256

  5. typedef struct _Node{
  6.     char value;
  7.     struct _Node *children[CSIZE];
  8. }Node;


  9. Node *createNode(char va){
  10.     Node * ret = (Node*)malloc(sizeof(Node));
  11.     ret->value = va;
  12.     memset(ret->children, 0, sizeof(void*)*CSIZE);
  13.         return ret;
  14. }


  15. int insert(Node* root, const char* str){
  16.     if(root == NULL || str == NULL)
  17.         return -1;
  18.     if(!*str)
  19.         return 1;
  20.     if(root->children[*str] == NULL){
  21.         Node* tmp = createNode(*str);
  22.         root->children[*str] = tmp;
  23.         printf("appen %c to %c\n", *str, root->value);
  24.     }
  25.     return insert(root->children[*str],str+1);
  26. }
  27. int search(Node* root, const char*str){
  28.     if(root == NULL || str == NULL)
  29.         return -1;
  30.     if(!*str) return 1;
  31.     if(root->children[*str] != NULL)
  32.         return search(root->children[*str],str+1);
  33.     return 0;
  34. }
  35. int main(){
  36.     Node* head = createNode((char)-1);
  37.     insert(head,"ab");
  38.     insert(head,"ac");
  39.     insert(head,"ad");
  40.     insert(head,"abc");

  41.     char* tar = "abc";
  42.     if(search(head, tar))
  43.         printf("found %s \n", tar);
  44.     else
  45.         printf("cannot find %s \n", tar);
  46. }

阅读(1118) | 评论(0) | 转发(1) |
0

上一篇:单链表的快排

下一篇:前n个素数的和

给主人留下些什么吧!~~