这里演示关于字典树的插入删除 查找
字典树的每个节点有26个子节点分别对应26个英文字母 ;每个节点还有个属性表示该节点是否为一个单词(从根节点到盖子节点)
参考http://www.cnblogs.com/archimedes/p/trie-tree.html
#include<iostream>
using namespace std;
struct Trie
{
Trie *next[26];
bool isword;
}root;
void insertchar(char* str);//函数声明
bool selectstr(char *str);
void delstr(char* str);
int main()
{
insertchar("abc");
insertchar("ab");
delstr("ab");
cout<<selectstr("abc");
getchar();
}
void insertchar(char* str)
{
//获取根节点
Trie *head = &root;
while(*str)
{
int index = *str-'a';
//使用NULL检验是否存在该字符
if(head->next[index]==NULL) //表示不存在该字符
head->next[index]=new Trie();//不存在则实例化该对象,并返回地址
str++; //指针运算 检验下一字符串
cout<<*str;
head = head->next[index]; //变为下一节点
}
head->isword=true;
}
bool selectstr(char *str)
{
Trie *head =&root;
while(*str)
{
int index=*str-'a';
if(head->next[index]==NULL)
return false;
str++;
head=head->next[index];
}
if(head->isword)
return true;
else
return false;
}
void delstr(char* str)
{
Trie* head=&root;
while(*str)
{
int index=*str-'a';
if(head->next[index]==NULL)
return;
str++;
head=head->next[index];
}
if(head->isword)
head->isword=false;
}