字典树

class Trie {
#define Trie_MAX_Letter_Num 26
public:
    Trie * next[Trie_MAX_Letter_Num];
    Trie * father;
    int cnt, mark;
    Trie() {
        cnt = 26;
        memset(next, NULL, sizeof(next));
        father = NULL;
        mark = 0;
    }
    void reset() {
        for (int i = 0; i < cnt; i++) {
            if (next[i] != NULL) {
                next[i]->reset();
            }
            delete next[i];
        }
        mark = false;
    }
    void Insert(char * ptr) {
        Trie * root = this;
        while (*ptr != '') {
            if (root->next[(*ptr) - 'a'] == NULL) {
                root->next[(*ptr) - 'a'] = new Trie;
                (root->next[(*ptr) - 'a'])->father = root;
            }
            root = (root->next[(*ptr) - 'a']);
            ptr++;
        }
        root->mark++;
    }
    bool Delete(char * ptr) {
        Trie * root = this;
        while (*ptr != '') {
            if (root->next[(*ptr) - 'a'] == NULL) {
                return false;
            }
            root = (root->next[(*ptr) - 'a']);
            ptr++;
        }
        root->mark--;
        return true;
    }
    Trie * Search(char * ptr) {
        Trie * root = this;
        while (*ptr != '') {
            if (root->next[(*ptr) - 'a'] == NULL) {
                return NULL;
            }
            root = (root->next[(*ptr) - 'a']);
            ptr++;
        }
        return root;
    }
};
View Code

void reset():释放内存
void Insert(char *):添加字符串
bool Delete(char *):删除字符串
Trie * Search(char *):查找字符串

原文地址:https://www.cnblogs.com/dramstadt/p/6222947.html