字典树的数据结构及基本算法的实现
2013-08-24 19:43
337 查看
#include <iostream> using namespace std; const int branchNum = 26;//声明常量 struct Trie_node{ bool isStr;//记录此处是否构成一个串。 Trie_node* next[branchNum];//指向各个子树的指针,下标0-25代表26字符 Trie_node():isStr(false){ memset(next,NULL,sizeof(next)); } }; class Trie{ public: Trie(); void insert(const char* word); bool search(char* word); void deleteTrie(Trie_node* root); private: Trie_node* root; }; Trie::Trie(){ root = new Trie_node(); } void Trie::insert(const char* word){ Trie_node* location = root; while(*word){ if(location->next[*word - 'a'] == NULL){//不存在则建立 Trie_node* tmp = new Trie_node(); location->next[*word - 'a'] = tmp; } location = location->next[*word - 'a']; //每插入一步,相当于有一个新串经过,指针要向下移 ++word; } location->isStr = true;//到达尾部,标记一个串 } bool Trie::search(char* word){ Trie_node* location = root; while(*word && location){ location = location->next[*word - 'a']; ++word; } return (location!=NULL && location->isStr); } void Trie::deleteTrie(Trie_node* root){ int i; for(i = 0 ; i < branchNum ; ++i){ if(root->next[i] != NULL){ deleteTrie(root->next[i]); } } delete root; } int main(){ Trie t; t.insert("a"); t.insert("abandon"); char* c = "abandoned"; t.insert(c); t.insert("abashed"); if(t.search("abashed")){ printf("true\n"); } }
相关文章推荐
- 字典树的数据结构及基本算法的实现
- 算法与数据结构--图的实现、基本操作及应用
- 算法与数据结构-单向链表的基本操作C语言实现
- Python数据结构与算法之字典树实现方法示例
- 算法与数据结构-队列的基本操作C语言实现
- 数据结构 P64-65 算法实现 循环队列的创建和基本操作
- 算法与数据结构-二叉树的基本操作C语言实现
- 算法与数据结构-栈的基本操作C语言实现
- 【数据结构和算法分析】单链表的基本实现
- 【数据结构和算法】用java简单的实现单链表的基本操作
- 实现一个算法来判断一个字符串中的字符是否唯一(即没有重复).不能使用额外的数据结构。 (即只使用基本的数据结构)
- 浅谈算法和数据结构(6):符号表及其基本实现
- 算法与数据结构-堆的基本操作C语言实现
- python数据结构与算法——图的基本实现及迭代器
- C++类模板 实现双向循环链表的基本算法 《数据结构》(C++版 北京科海)中摘抄
- 浅谈算法和数据结构: 六 符号表及其基本实现
- 浅谈算法和数据结构: 六 符号表及其基本实现
- 数据结构基本算法java实现
- 算法与数据结构--图的实现、基本操作及应用