接 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;
}