字典树
来源:互联网 发布:注射死刑 知乎 编辑:程序博客网 时间:2024/06/05 09:32
//字典树的插入和删除操作
#define MAX_SIZE 25
const int LinkSize = 27;typedef enum {ELEM=0,BRCH}NodeType;
typedef struct
{
char ch[MAX_SIZE + 1];
int curSize;
}KeyType;//关键码类型
typedef struct {}Record;
typedef struct
{
KeyType key;
Record *recptr;
}ElemType; //元素节点
struct TrieNode;
typedef struct
{
TrieNode * Link[LinkSize];
}BrchType; //分支节点
//字典树节点类型
typedef struct TrieNode
{
NodeType utype;
union
{
ElemType elem;
BrchType brch;
};
}TrieNode;
class TrieTree
{
private:
TrieNode *root;
static TrieNode* BuyNode()
{
TrieNode * s = (TrieNode*)malloc(sizeof(TrieNode) * 1);
if (s == NULL)return NULL;
memset(s, 0, sizeof(*s));
return s;
}
static TrieNode *BuyElem(ElemType x)
{
TrieNode *s = BuyNode();
if (s != NULL)
{
s->utype = ELEM;
s->elem = x;
}
return s;
}
static TrieNode* BuyBrch(TrieNode *&ptr, int pos)
{
TrieNode *s = BuyNode();
if (s != NULL)
{
s->utype = BRCH;
int index = FindIndex(ptr->elem.key, pos);
s->brch.Link[index] = ptr;
}
return s;
}
static void FreeNode(TrieNode *s)
{
free(s);
}
static int FindIndex(KeyType const x, int pos)
{
int index = 0;
if (x.curSize > pos)
{
index = x.ch[pos] - 'a' + 1;
}
return index;
}
//以下是插入操作,pos记录了匹配到的当前单词的字母位置
static bool Insert(TrieNode *&ptr, const ElemType &x,int pos)
{bool res = false;
if (ptr == NULL)
{
ptr = BuyElem(x);
res = true;
}else if (ptr->utype == BRCH)
{
int index = FindIndex(x.key, pos);
res = Insert(ptr->brch.Link[index], x, pos + 1);
}else if(ptr->utype == ELEM)
{
if (strcmp(x.key.ch, ptr->elem.key.ch) != 0)
{
ptr = BuyBrch(ptr, pos);
int index = FindIndex(x.key, pos);
res = Insert(ptr->brch.Link[index], x, pos + 1);
}
}
return res;
}
//查找元素,相对简单
TrieNode* FindValue(TrieNode *ptr, KeyType x,int pos)
{
if (ptr == NULL)return NULL;
else if (ptr->utype == ELEM)
{
return strcmp(ptr->elem.key.ch, x.ch) == 0 ? ptr:NULL;
}
else if (ptr->utype == BRCH)
{
int index = FindIndex(x, pos);
return FindValue(ptr->brch.Link[index],x,pos + 1);
}
}
public:
TrieTree() :root(NULL){}
~TrieTree(){}
bool Insert(const ElemType &x)
{
bool rs = false;
if (x.key.curSize > 0)
{
rs = Insert(root, x,0);
}
return rs;
}
TrieNode *FindValue(KeyType x)
{
return FindValue(root, x,0);
}
bool Remove(const KeyType &x)
{
bool res = false;
TrieNode *s = FindValue(x);
if (s != NULL && s->utype==ELEM)
{
FreeNode(s);
s = NULL;
res = true;
}
return res;
}
};
0 0
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树。。
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 1036. 跟奥巴马一起编程(15)
- yii2 命名空间
- 2分钟读懂Hadoop和Spark的异同
- 深度学习方法(六):神经网络weight参数怎么初始化
- 1037. 在霍格沃茨找零钱(20)
- 字典树
- 安装jdk1.8
- 正则替换特殊字符
- Androidx学习笔记(33)---新闻客户端之布局
- Theano的一个关于signal,signal/conv,signal/downsample的错误
- 【算法-字符串】【WERTYU】
- JAVA中的内部类
- iptables(一)
- 【NYOJ】[75]日期计算