Trie-Implementierung in C++

Ich versuche zu implementieren, die versuchten, wie gezeigt, auf die TopCoder Seite. Ich bin zu modifizieren, ein bit zum speichern die Telefonnummern der Nutzer. Ich bin immer segmentation fault. Kann jemand bitte zeigen Sie den Fehler.

 #include<iostream>
 #include<stdlib.h>
 using namespace std;

 struct node{
int words;
int prefix;
long phone;
struct node* children[26];
 };

struct node* initialize(struct node* root) {
    root = new (struct node);   
    for(int i=0;i<26;i++){
    root->children[i] = NULL;
    }
    root->word = 0;
    root->prefix = 0;
    return root;
 }

int getIndex(char l) {
    if(l>='A' && l<='Z'){
    return l-'A';
    }else if(l>='a' && l<='z'){
    return l-'a';
    }
 }

  void add(struct node* root, char * name, int data) {

    if(*(name)== '\0') {
        root->words = root->words+1;
        root->phone = data;
    } else {        
        root->prefix = root->prefix + 1;
        char ch = *name;
        int index = getIndex(ch);
        if(root->children[ch]==NULL)    {
            struct node* temp = NULL;
            root->children[ch] = initialize(temp);
        }
        add(root->children[ch],name++, data);
    }
 }

 int main(){
     struct node* root = NULL;
     root = initialize(root);
     add(root,(char *)"test",1111111111);
     add(root,(char *)"teser",2222222222);
         cout<<root->prefix<<endl;
     return 0;
  }

Wurde eine neue Funktion Hinzugefügt nach der Herstellung von vorgeschlagenen änderungen an:

 void getPhone(struct node* root, char* name){
     while(*(name) != '\0' || root!=NULL) {
         char ch = *name;
         int index = getIndex(ch);
         root = root->children[ch];
         ++name;
     }
     if(*(name) == '\0'){
         cout<<root->phone<<endl;
     }
 }
Meinst du Marina?
"Hausaufgaben" - tag ist veraltet inzwischen ...
ja .. Sorry .. 😛 .. geändert..
In der getIndex () - Funktion nicht, du meinst "return l-'A'"?
Ein debugger wird dir zeigen, Ihre Fehler in etwa 1,5 Sekunden. Es verwenden.

InformationsquelleAutor Fox | 2013-04-20

Schreibe einen Kommentar