I have the following which works but was wondering if there's a better way. Better meaning more efficient and or more compact.
The function checks a trie to see if the word is in the trie.
bool check(const char *word)
{
int nodeIdx = hash(word);
if (nodeIdx < 0)return false;
nodeWords * searchNode;
searchNode = nodeArray[nodeIdx]; //nodeArray is global
bool whileFlag = true, returnFlag = false;
do
{
if (strcmp(word,searchNode->word) == 0 )
{
whileFlag = false;
returnFlag = true;
}
else if (strcmp(word,searchNode->word) < 0 )
{
if(searchNode->left == NULL)
{
whileFlag = false;
}else{
searchNode = searchNode->left;
}
}else{
if(searchNode->right == NULL)
{
whileFlag = false;
}else{
searchNode = searchNode->right;
}
}
}while (whileFlag);
free(searchNode);
return returnFlag;
}
for instance, we could rewrite the function this way:
bool check(const char *word)
{
int nodeIdx = hash(word);
if (nodeIdx < 0)return false;
nodeWords * searchNode;
searchNode = nodeArray[nodeIdx];
bool returnFlag = false;
do
{
if (strcmp(word,searchNode->word) == 0 )returnFlag = true;
else if (strcmp(word,searchNode->word) < 0 && searchNode->left != NULL) searchNode = searchNode->left;
else if (strcmp(word,searchNode->word) > 0 && searchNode->right != NULL) searchNode = searchNode->right;
}while (searchNode->left != NULL || searchNode->right != NULL || strcmp(word,searchNode->word) == 0);
return returnFlag;
}
Aucun commentaire:
Enregistrer un commentaire