Jakiś czas temu skończyłem całe drzewo Trie. Niestety musiałem je później przerobić na PATRICIA ^^ (już się z tym uporałem :P). Tak czy siak, chciałem się podzielić podstawowymi operacjami Trie. Drzewo indeksujące PESEL. Klasy person nie zamieszczałem, można taką stworzyć samemu :P. Język oczywiście C++ :).
class node {
public:
node* _[_TSIZE];
person* x;
node() {
p = NULL;
x = NULL;
for (int i = 0; i < _TSIZE; i++)
_[i] = NULL;
}
~node() {
if (x) delete x;
for (int i = 0; i < _TSIZE; i++)
if (_[i]) delete _[i];
}
};
class registry {
private:
node* root;
node* getnode(string);
public:
inline void printall(node*);
registry();
~registry();
void add(string, string, string, bool);
void remove(string);
person* getperson(string);
};
registry::registry() {
root = new node();
}
registry::~registry() {
delete root;
}
node* registry::getnode(string pesel) {
node* tmp = root;
for (int i = 0, indx = pesel[i] - 48; pesel[i]!='\0'; indx = pesel[++i] - 48) {
if (tmp -> _[indx] == NULL)
return NULL;
tmp = tmp -> _[indx];
}
return tmp;
}
inline void registry::printall(node* start = NULL) {
if (!start)
start = root;
if (start -> x)
start -> x -> display();
for (int i = 0; i < _TSIZE ; i++)
if (start -> _[i])
printall(start -> _[i]);
}
void registry::add(string pesel, string imie, string nazwisko, bool silent = false) {
node* tmp = root;
for (int i = 0, indx = pesel[i] - 48; pesel[i]!='\0'; indx = pesel[++i] - 48) {
if (tmp -> _[indx] == NULL)
tmp -> _[indx] = new node();
tmp = tmp -> _[indx];
}
if (tmp -> x) {
if (!silent)
cout << _MSG_EXISTS << endl;
} else {
tmp -> x = new person(pesel,imie,nazwisko);
if (!silent)
cout << _MSG_DONE << endl;
}
}
void registry::remove(string pesel) {
node* tmp = getnode(pesel);
if (!tmp || !tmp -> x)
cout << _MSG_NOTFOUND << endl;
else {
if (tmp -> x -> children -> size() == 0 && tmp -> x -> parent -> size() == 0) {
delete tmp -> x;
tmp -> x = NULL;
cout << _MSG_DONE << endl;
} else {
cout << _MSG_DELFAIL << endl;
}
}
}
person* registry::getperson(string pesel) {
node* tmp = getnode(pesel);
if (!tmp || !tmp -> x) {
cout << _MSG_NOTFOUND << endl;
return NULL;
} else
return tmp -> x;
}