1. 程式人生 > >字典樹模板(有待更新,連結串列版)

字典樹模板(有待更新,連結串列版)

連結串列版:空間小,時間大。

陣列版:空間大,時間小

struct node
{
    int num;
    node *next[maxn];
};

//字典樹
class Tree{
public:
    node *head;
    //建構函式
    Tree()
    {
        head = New();
    }
    //建立一個新節點
    node* New()
    {
        node *p = new node();
        for (int i = 0; i < maxn; ++i)
        {
            p
->next[i] = NULL; } p->num = 0; return p; } //插入一個字串 void insert(char *str) { int len = strlen(str); node *t, *p = head; for (int i = 0; i < len; ++i) { int c = str[i] - 'a'; if (p->next[c] == NULL) { t
= New(); //建立新的節點 p->next[c] = t; } p = p->next[c]; p->num++; } } int find(char *str) { node *p = head; int len = strlen(str); for (int i = 0; i < len; ++i) { int c = str[i] - '
a'; if (p->next[c] == NULL) return 0; //不存在這樣的字串 p = p->next[c]; } return p->num; } };

良心模板