Trie[字典树] 数据结构及基本操作集
2017-08-02 13:55
495 查看
#include <iostream> #include <stdio.h> #include <cstring> #include <algorithm> #include <vector> using namespace std; #define Max 26 typedef struct TrieNode *Trie; struct TrieNode { Trie next[Max]; int num; TrieNode() { for (int i = 0; i < Max; i++) next[i] = NULL; num = 0; } }; void Insert(Trie root,char *s) { Trie p = root; for (int i = 0; s[i]; i++) { int t = s[i]-'a'; if (p->next[t] == NULL) p->next[t] = new TrieNode; p = p->next[t]; } p->num++; } void Delete(Trie root, char *s) { int len = strlen(s); Trie p = root; for (int i = 0; i < len; i++) { int t = s[i]-'a'; if (p->next[t] == NULL) return; p = p->next[t]; } p->num--; } bool Search(Trie root, char *s) { Trie p = root; if (p == NULL) return 0; int len = strlen(s); for (int i = 0; i < len; i++) { int t = s[i]-'a'; if (p->next[t] == NULL) return 0; p = p->next[t]; } return p->num > 0; } void PrintDic(Trie root, vector<vector<char> > &words, vector<char> &word) { if (root == NULL) return; if (root->num > 0) words.push_back(word); for (int i = 0; i < Max; i++) { if (root->next[i]) { word.push_back('a'+i); PrintDic(root->next[i], words, word); word.pop_back(); } } } void FreeTrie(Trie root) { for (int i = 0; i < Max; i++) { if (root->next[i] != NULL) FreeTrie(root->next[i]); } delete root; } int main() { freopen("1.txt", "r", stdin); Trie root = new TrieNode; char s[300]; while (cin >> s) { Insert(root, s); } //char temp[50] = "avvvvefaf"; //cout << Search(root, temp); //Delete(root, temp); //cout << Search(root, temp); vector<char> word; vector<vector<char> >words; PrintDic(root, words, word); for (int i = 0; i < words.size(); i++) { for (int j = 0; j < words[i].size(); j++) { printf("%c", words[i][j]); } printf("\n"); } return 0; }
相关文章推荐
- 链栈的基本操作-数据结构
- [数据结构]基本概念、单链表操作
- B树(B-Tree)的由来、数据结构、基本操作以及数据库索引的应用
- 实战数据结构(5)_双向循环链表的基本操作
- 数据结构(第二天)单链表的基本操作,创建单链表,头插法,尾插法,删除节点,查询节点
- 数据结构笔记(一)线性表的顺序表示和基本操作及其顺序表实现的集合运算(A-B)U(B-A)实例
- 实战数据结构(5)_双向循环链表的基本操作
- 数据结构与算法———顺序表的基本操作
- 数据结构之队列的基本操作入队出队初始化删除-c++代码实现及运行实例结果
- 数据结构与算法——单链表的基本操作
- 数据结构(4):双向链表的基本操作
- 数据结构顺序表相关基本操作练笔
- 经典数据结构之一维矩阵的基本操作
- 数据结构之顺序串的基本操作
- 数据结构—链表-单链表基本操作实现
- 3335 数据结构实验之栈与队列八:栈的基本操作
- 【数据结构】顺序栈的基本操作操作---C/C++
- 数据结构之队列的基本操作入队出队初始化删除-c++代码实现及运行实例结果
- (大数据工程师学习路径)第一步 Linux 基础入门----目录结构及文件基本操作
- MySQL数据表的基本操作二:表结构修改