Trie树实现二
2013-09-26 20:03
176 查看
接 Trie树实现一,采用链表形式来实现状态的转换!
#include <iostream> #include <list> #include <algorithm> #include <functional> using namespace std; class Node; struct EqualTo : public binary_function<pair<char, Node*>, char, bool> { public: bool operator() (pair<char, Node*> obj, char ch) const { return obj.first == ch; } }; class Node { public: list<pair<char, Node*> > next; bool leaf; Node():leaf(false){}; }; class ListTrie { public: Node root; bool insert(const char*& key); bool remove(const char*& key); bool retrival(const char*& key); }; bool ListTrie::insert(const char*& key) { Node* cur = &root; int i = 0; while( key[i] ) { list<pair<char, Node*> >::iterator iter = find_if( (cur->next).begin(), (cur->next).end(), bind2nd(EqualTo(), key[i]) ); if( iter == (cur->next).end() ) { (cur->next).push_front( pair<char, Node*>(key[i], new Node()) ); iter = (cur->next).begin(); } cur = iter->second; ++i; } return cur->leaf?false:cur->leaf=true; } bool ListTrie::remove(const char*& key) { Node* cur = &root; int i = 0; while( key[i] ) { list<pair<char, Node*> >::iterator iter = find_if( (cur->next).begin(), (cur->next).end(), bind2nd(EqualTo(), key[i]) ); if( iter == (cur->next).end() ) { return false; } cur = iter->second; ++i; } cur->leaf = false; return true; } bool ListTrie::retrival(const char*& key) { Node cur = root; int i = 0; while( key[i] ) { list<pair<char, Node*> >::iterator iter = find_if( cur.next.begin(), cur.next.end(), bind2nd(EqualTo(), key[i]) ); if( iter == cur.next.end() ) return false; cur = *( iter->second ); ++i; } return cur.leaf; } void Test() { ListTrie trie; const char* str[] = {"baby", "badge", "bachelor", "jar", "java", "javac", "javap", "bad"}; for(int i = 0; i < 8; ++i) { bool r = trie.insert( str[i] ); if( r ) cout << "insert " << str[i] << endl; else cout << "fail to insert " << str[i] << endl; } for(int i = 0; i < 8; ++i) { bool r = trie.retrival( str[i] ); if( r ) cout << "find " << str[i] << endl; else cout << "fail to find " << str[i] << endl; trie.remove( str[i] ); r = trie.retrival( str[i] ); if( r ) cout << "find " << str[i] << endl; else cout << "fail to find " << str[i] << endl; } } int main() { Test(); return 0; }
相关文章推荐
- trie树(字典树)java实现
- Trie树的DAT实现
- Trie树的实现
- trie树Java实现
- 高级数据结构的学习与实现之 Trie树,字典树
- 用Trie树实现词频统计和单词查询
- 用二叉树实现Trie树
- 实用算法实现-第 7 篇 Trie树
- [算法] trie树实现
- Trie树实现一
- Trie树 c++实现
- Trie树|字典树的简介及实现
- 【数据结构-trie树】trie数实现单词查询和单词统计
- Trie树实现三----双数组trie树
- Java实现Trie树
- Trie树(c++实现)
- Trie树的Java实现
- Trie树的创建、插入、查询的实现 Add and Search Word
- Trie树的C++实现
- 标准trie树的Java实现