这个程序是一个二叉搜索树的插入函数,我完全理解它背后的概念和一切......我唯一不明白的是这一行:
BTree root = NULL;
所以据我所知root是一个指针,它不指向任何东西,这就是为什么它的 NULL ,但为什么它的数据类型是BTree,它不应该是_btree吗?我知道有一个指针 *Btree 但它不是数据类型,所以怎么可能。
#include <stdio.h>
#include <stdlib.h>
typedef struct _btree
{
int v;
struct _btree *left, *right;
} BTreeRec , *BTree;
BTree insert(BTree t, int v)
{
if (t == NULL) {
t = (BTree)malloc(sizeof(BTreeRec)); t->v = v;
t->left = t->right = NULL;
} else if (v < t->v)
t->left = insert(t->left, v);
else
t->right = insert(t->right, v); return t;
}
int main() {
BTree root = NULL;
}
线路:
typedef struct _btree
{ int v;
struct _btree *left, *right;
} BTreeRec , *BTree;
相当于:
struct _btree {
int v;
struct _btree *left;
struct _btree *right;
};
typedef struct _btree BTreeRec;
typedef struct _btree * BTree;
typedef 就像名称的别名。并且*
“坚持”它。每次您写的BTree
内容都struct _btree *
与包含星号的内容相同。所以你的代码相当于:
struct _btree *insert(struct _btree *t, int v) {
if (t == NULL) {
t = malloc(sizeof(struct _btree));
t->v = v;
t->left = NULL;
t->right = NULL;
} else if (v < t->v) {
t->left = insert(t->left, v);
} else {
t->right = insert(t->right, v);
}
return t;
}
int main() {
struct _btree *root = NULL;
}
可读性提高了 500%,意图也更加清晰。代码就像一首诗——读起来一定很舒服。作为一般规则,不鼓励使用 typedef 指针(除非您正在实现特定情况,例如您特别想使用它们的不透明库)。主观上:我也不喜欢使用typedef
来隐藏struct
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句