當前我試圖將我的文件中的每個單獨的行存儲到一個字符串中,然後將其存儲在二叉搜索樹中,但會出現問題。出於某種原因,當我打印我的BST時,只輸出最後一行,而不是前三行。下面是我的代碼。使用fgets讀取文件中的行到二叉搜索樹
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
int count;
char* key;
struct node* left;
struct node* right;
};
struct node *newNode(char* item)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = NULL;
temp->right = NULL;
temp->count = 1;
return temp;
};
void printInorder(struct node* root)
{
if(root != NULL)
{
printInorder(root->left);
printf("%s \n", root->key);
printInorder(root->right);
}
}
struct node* insert(struct node* node, char* key)
{
if(node == NULL)//When tree is empty
return newNode(key);
if(strcmp(key, node->key) < 0)
node->left = insert(node->left, key);
if(strcmp(key, node->key) > 0)
node->right = insert(node->right, key);
return node;
};
int main()
{
struct node *root = NULL;
int i = 0;
char str[100];
FILE* fp;
fp = fopen("textFile.txt", "r");
if ((fp = fopen("textFile.txt","r")) == NULL)
{
printf("Could not open textFile.txt\n");
exit(1);
}
while(fgets(str, 100, fp) != NULL)
{
++i;
root = insert(root, str);
printf("%3d: %s", i, str);
}
printf("bst printed\n");
printInorder(root);
return 0;
}
TextFile.txt的包含
bob is working.
david is a new hire.
alice is bob's boss.
charles doesn't like bob.
而當BST被印刷,其輸出是最後一個 查爾斯不喜歡鮑勃唯一線。
任何幫助真的不勝感激。
非常感謝您的幫助,我非常感謝您付出的努力,不僅爲我解決問題,還一步一步解釋我的代碼中發生了什麼,以便我能更好地理解它。非常感謝! – Kevag6