Trie树实现二

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值