Greetings,
I did notice a few typographical syntax errors, and a node system error. Let's start off with the syntax errors, as they are easy to fix.
insertNode()
Taking a look inside your
insertNode code, you have a few
if-else statements in there. These statements may result in faulty executions; see why:
else if ( root -> left = NULL ) { As seen here, in red, your program will never check if
root->left is "equal to" NULL. That's why C comes with equality operators. An equality operator is one that tests a condition such as "is less than", "is greater than", and "is equal to". Here is a closer look of equality operators:
name symbol sample usage result
is less than < bool result = (1 < 2) true
is greater than > bool result = (2 > 5) false
is equal to == bool result = (8 == 8) true
is less than or equal to <= bool result = (45.7 <= 42.3) false
is greater than or equal to >= bool result = (25.6 >= 12.9) true
is not equal to != bool result = (12 != 12) false
Back on track, all you have to do is change the = to == in your
if statements:
else if ( root -> left == NULL ) { makenode()
This fix may be a bit more difficult than the last. Let's see why. Most node additions take place like this. First, if the node doesn't exist [NULL] then allocate memory to the node, set any data, and set left and right to NULL. Though usually after this it depends on how you want your node. Do you want it to check for previous entrance, or not.
For example, if you had a node and wanted to check for previous entrance of a word and so forth, it would work as the following:
Node* Node::addNode(Node *p, char *word) {
int cond;
if (p == NULL) {
p = (Node *)malloc(sizeof(Node));
p->word = strdup(word);
p->count = 1;
p->left = p->right = NULL;
}else if ((cond = strcmp(word, p->word)) == 0)
p->count++; // Repeated word
else if (cond < 0) // Less than into left subtree
p->left = addNode(p->left, word);
else // Greater than into right subtree
p->right = addNode(p->right, word);
return p;
} That was just a rough draft example. It may help you understand the syntax of a node though. Here is a useful tutorial on
Linked List that may interest you.
If you have further questions, please feel free to ask.
-
Stack
Overflow