- 论坛徽章:
- 1
|
这段时间正好学C++ 加之以前了解了一下trie 写了一个程序 贴出来让大家批批
- #include <iostream>
- #include <queue>
- using namespace std;
- class trieNode{
- private:
- char key;
- int value;
- trieNode *next;
- trieNode *child;
- public:
- friend class trie;
- trieNode():key('\0'),value(-1),next(NULL),child(NULL){}
- trieNode(char key,int value,trieNode *next,trieNode *child);
- void setValue(int value){this->value = value;}
- };
- trieNode::trieNode(char key,int value,trieNode *next,trieNode *child){
- this->key = key;
- this->value = value;
- this->next = next;
- this->child = child;
- }
- class trie{
- private:
- trieNode head;
- public:
- trie():head('\0',-1,NULL,NULL){}
- void addItem(const char *str,int value);
- void printTrie();
- void printNode(trieNode *first);
- int findPre(const char *str);
- };
- void trie::addItem(const char *str,int value){
- const char *p;
- trieNode *root;
- trieNode *t;
- trieNode *pre;
- trieNode *node;
- if(str == NULL){
- return ;
- }
- root = &head;
-
- for(p = str;;p++){
- pre = NULL;
- for(t = root->child;t != NULL;t = t->next){
- if(t->key == *p){
- break;
- }
- pre = t;
- }
- if(t == NULL){
- node = new trieNode(*p,-1,NULL,NULL);
- if(node == NULL){
- return ;
- }
- if(pre == NULL){
- root->child = node;
- }
- else{
- pre->next = node;
- }
- root = node;
- }
- else{
- root = t;
- }
- if(*p == '\0'){
- node->setValue(value);
- break;
- }
- }
- }
- void trie::printTrie(){
- queue<trieNode *> triequ[2];
- trieNode *p;
- trieNode *root;
- int i = 0;
-
- triequ[i].push(&head);
- while(!triequ[i].empty()){
- while(!triequ[i].empty()){
- root = triequ[i].front();
- triequ[i].pop();
- if(root == NULL){
- cout << endl;
- continue;
- }
- for(p = root->child;p != NULL;p = p->next){
- triequ[1 - i].push(p);
- cout << p->key << "(" << p->value << "," << root->key << ")\t";
- }
- }
- cout << endl;
- i = 1 - i;
- }
- }
- int trie::findPre(const char *str){
- int count = 0;
- const char *p;
- trieNode *root;
- trieNode *t = NULL;
- queue<trieNode *> triequ;
-
- if(str == NULL || *str == '\0'){
- return count;
- }
- root = &head;
-
- for(p = str;*p != '\0';p++){
- for(t = root->child;t != NULL;t = t->next){
- if(t->key == *p){
- break;
- }
- }
- if(t == NULL){
- return count;
- }
- root = t;
- }
- triequ.push(t);
- while(!triequ.empty()){
- root = triequ.front();
- triequ.pop();
- for(t = root->child;t != NULL;t = t->next){
- triequ.push(t);
- if(t->key == '\0'){
- count++;
- }
- }
- }
-
- return count;
- }
- int main(){
- trie t;
- t.addItem("banana",1);
- t.addItem("bamboo",2);
- t.addItem("bee",3);
- t.addItem("absolute",4);
- t.addItem("bane",5);
- t.addItem("adam",6);
- t.addItem("bra",7);
- t.addItem("boost",8);
- t.printTrie();
- cout << t.findPre("bo") << endl;
-
- return 0;
- }
复制代码
[ 本帖最后由 yecheng_110 于 2008-4-10 09:57 编辑 ] |
|