正在插入Trie,NULL指针

Inserting into a Trie, NULL pointers

本文关键字:NULL 指针 Trie 插入      更新时间:2023-10-16

我有一个关于Trie数据结构的特定问题,以及我的代码出了什么问题。当我递归调用insert时,函数参数root总是为NULL。这是我的代码:

代码:

//subNodes is an array of TrieNode pointers that contains indices for all letters in the alphabet
bool insert(const string& word, TrieNode* root, int curI = 0)
//PRE:  word must be a valid word in a dictionary
//POST: True when a word is inserted into the Trie, false otherwise
{
    if(curI >= word.length())        //word has been scanned fully
    {
        root->isWord = true;
        return true;
    }
    else                             //word has more letters to be scanned
    {
        if(root->subNodes[word[curI] - 'A'] == NULL)    //if the current letter of the word is not in the trie
        {                                            //   insert the letter and advance the current letter of the word
            root->subNodes[word[curI] - 'A'] = new TrieNode(word[curI]);
            insert(word, root->subNodes[word[curI] - 'A'], curI++);
        }
        else                                         //if the currrent letter of the word is in the trie
        {                                            //   advance the current letter of the word
            insert(word, root->subNodes[word[curI] - 'A'], curI++);
        }
    }
}

我通过用subNodes[word[13]]替换subNodes[word[curI] - 'A']来测试这一点(13是字母表中N的索引,而我测试的不是单词),并且该调用的根不再为NULL。因此,索引出现了问题。有人知道出了什么问题吗?我考虑过使用C++映射或向量。有人对使用数组有意见吗?

您的意思是++curl吗?即将递增的值传递给递归调用?目前,由于curl++是后增量的,所以您将相同的值传递到每个递归中。无论如何,只写curl + 1可能更容易,因为您不再需要curl值。

这里有两个问题。

  1. 在两个序列点之间,如果变量被修改,则只能访问该变量以确定要存储的新值。在您的代码中,当您调用insert()时,curI会递增,并且还会被访问以作为参数传递。这是错误的
  2. C标准没有定义函数参数的评估顺序

http://en.wikipedia.org/wiki/Sequence_point

http://c-faq.com/expr/seqpoints.html

以下内容将解决此问题。

insert(word, root->subNodes[word[curI] - 'A'], curI);
curI++;