void BST::insert(string word)
{
insert(buildWord(word),root);
}
//Above is the gateway insertion function that calls the function below
//in order to build the Node, then passes the Node into the insert function
//below that
Node* BST::buildWord(string word)
{
Node* newWord = new Node;
newWord->left = NULL;
newWord->right = NULL;
newWord->word = normalizeString(word);
return newWord;
}
//The normalizeString() returns a lowercase string, no problems there
void BST::insert(Node* newWord,Node* wordPntr)
{
if(wordPntr == NULL)
{
cout << "wordPntr is NULL" << endl;
wordPntr = newWord;
cout << wordPntr->word << endl;
}
else if(newWord->word.compare(wordPntr->word) < 0)
{
cout << "word alphabetized before" << endl;
insert(newWord,wordPntr->left);
}
else if(newWord->word.compare(wordPntr->word) > 0)
{
cout << "word alphabetized after" << endl;
insert(newWord, wordPntr->right);
}
else
{
delete newWord;
}
}所以我的问题是:我在外部调用网关insert() (数据流入也没有问题),每次它告诉我root或初始Node*为空。但应该只在第一次插入之前出现这种情况。每次调用该函数时,它都会将newWord放在根目录下。需要说明的是:这些函数是BST类的一部分,root是Node*和BST.h的私有成员
这很可能是很明显的,我只是盯着看了太久。任何帮助都将不胜感激。另外,这是一个学校指定的项目。
最好的
发布于 2012-07-20 14:48:17
正如user946850所说,变量wordPntr是一个局部变量,如果您将其更改为指向其他变量,它将不会反映在调用函数中。
有两种方法可以解决这个问题:
通过使用指向指针的指针,
void BST::insert(节点*newWord,节点* *wordPntr ) { // ... *wordPntr= newWord;// ... }
你这样叫它:
&rootPntr);
void BST::insert(节点*newWord,节点*&wordPntr) { //此处或调用方中没有任何更改// ... }
为了帮助您更好地理解这一点,我建议您阅读更多关于变量的作用域和生存期的内容。
发布于 2012-07-20 10:32:00
赋值wordPntr = newWord;对于insert函数来说是本地的,在这种情况下它应该以某种方式设置树的根。
https://stackoverflow.com/questions/11572041
复制相似问题