私はC言語を新しくしており、主に三項探索木のデータ構造をコード化しようとしています。私は、有効なchar入力が渡されているという前提の下で作業しています。私は自分のinsert関数にいくつかの問題があります。最後のTSTnodeにもstrの最後の文字が保持される元の文字列を挿入することに注意してください。ここで三項探索木の挿入関数 - C
は、私はここで、これまで
struct TSTnode {
char* word; // NULL if no word ends here
char self;
struct TSTnode *left, *sub, *right;
};
int insert_tst(struct TSTnode** tree, const char* str) {
return _insert(tree, str, 0);
}
int _insert(struct TSTnode** tree, const char* str, int position) {
if((*tree) == NULL) {
*tree = new_tst_node(*(str+position));
position = position + 1;
if(*(str+position) == '\0') {
(*tree)->word = strcpy((*tree)->word,str);
return 1;
}
}
else if ((*tree)->self > *(str+position)) {
position = position + 1;
_insert(&((*tree)->left), str, position);
}
else if ((*tree)->self < *(str+position)) {
position = position + 1;
_insert(&((*tree)->right), str, position);
}
else {
position = position + 1;
_insert(&((*tree)->sub), str, position);
}
return 0;
}
struct TSTnode* new_tst_node(char self) {
struct TSTnode* newNode = (struct TSTnode*) malloc(sizeof(struct
TSTnode));
if (newNode == NULL) {
return NULL;
}
newNode->word = NULL;
newNode->self = self;
newNode->left = NULL;
newNode->right = NULL;
newNode->sub = NULL;
return newNode;
}
を持っているものである私がテストしてい方法です:
struct TSTnode* tree = NULL;
char* words[1] = {"hello"};
for (int i = 0; i < 1; i++) {
if (insert_tst(&tree, words[i]) == 0) {
//print some error
}
else { //success }
EDITを - 私の問題は私の条件分岐のどれも取らされていないことをされ、挿入機能単に0
あなたのご質問はありますか? – Miket25
問題がある場合は、その問題を説明してください。何が間違っているのかを推測するのはずっと難しいです。 – tadman
ファイルスコープでアンダースコアで始まる名前は、実装用に予約されています。あなたはそれらを使用してはいけません。 – Olaf