Я dry запустил эту реализацию попыток с парным классом, но он не дает ожидаемого результата. Что я делаю не так? - PullRequest
0 голосов
/ 21 марта 2020
#include<iostream>
using namespace std;
class trieNode{
public:
    int data;
    bool isTerminal;
    trieNode ** children;
    trieNode(int data){
        this->data = data;
        children = new trieNode*[26];
        for(int i=0;i<26;i++){
            children[i] = NULL;
        }
        isTerminal = false;
    }
};

class Pair{
public:
bool exist;
trieNode* address;
Pair(){
    exist = false;
    address = NULL;
}
};

class Trie{
public:
trieNode *root;

Trie(){
    root = new trieNode('\0');
}
// for programmer
private:
    void insert(trieNode* root,string word){
        //base case
        if(word.size() == 0){
            root->isTerminal = true;
            return ;
        }
        // small calculation
        int index = word[0] - 'a';
        trieNode *child;
        if(root->children[index] != NULL){
            child = root->children[index];
        }
        else{
            child = new trieNode(word[0]);
            root->children[index] = child;
        }

        // recursion
        insert(child,word.substr(1));

    }
    // for user
public:
void insertWord(string word){

    insert(root,word);
}
// for programmer
private:
void deleteWord(trieNode* root, string word){
    if(word.size() == 0){
        root->isTerminal = false;
        return;
    }
    int index = word[0] - 'a';
    trieNode *child;
    if(root->children[index] != NULL){
        child = root->children[index];
    }
    else{
        return;
    }
    deleteWord(child,word.substr(1));

    if(child->isTerminal == false){
        for(int i=0;i<26;i++){
            if(child->children[i] != NULL)
            return;
        }
        delete child;
        root->children[index] = NULL;
    }       
}
// delete word 
//for user
public:
void deleteWord(string word){
    deleteWord(root,word);
}
// search a sting in trie
//function for programmer
// i used a pair class as return type brcause i want to return if word exists then return it's 
address too
// i.e return a bool = true and adress where the word ends
private:
Pair find(trieNode *root, string word){
    Pair p;
    if(word.size() == 0){
        Pair p;
        p.address = root;
        if(root->isTerminal == true)
            p.exist = true;
        else
            p.exist = false;
        return p;
    }
    trieNode *child;
    int index = word[0]-'a';
    if(root->children[index] == NULL){
        Pair p;
        p.address = root;
        p.exist =  false;
        return p;
    }
    else{
        child = root->children[index];
        p = find(child, word.substr(1));
    }
}
// search a string in the trie
// function for user
public:
Pair findstr(string word){
Pair p;
p = find(root,word);
return p;
}
};

int main(){
Trie t;
t.insertWord("sucess");
t.insertWord("s");
t.insertWord("a");
Pair p;
p = t.findstr("sucess");
cout<< p.address->data <<" "<< p.exist<<endl;
p = t.findstr("s");
cout<< p.address->data <<" "<< p.exist<<endl; 
p = t.findstr("a");
cout<< p.address->data <<" "<< p.exist;

Я использую класс пары для реализации функции findstr, которая находит слово в tr ie и возвращает 2 вещи: bool и адрес последнего trieNode слова, для что я использовал класс пары, в этом коде он должен возвращать адрес в шестнадцатеричном и true для всех трех, но я вижу только значения мусора

}

1 Ответ

1 голос
/ 21 марта 2020

Здесь есть одна проблема

else{
    child = root->children[index];
    p = find(child, word.substr(1));
}

, которая должна быть

else{
    child = root->children[index];
    p = find(child, word.substr(1));
    return p;
}

Компилятор должен был выдать вам предупреждение о пропущенном операторе возврата. Вы игнорировали это?

Может быть много других проблем с кодом. Как уже было сказано, нужно использовать отладчик . Гораздо быстрее способ исправить ваши ошибки, чем спрашивать на SO.

...