您的位置:首页 > 编程语言 > Go语言

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm 算法