![](/img/trans.png)
[英]recursive function that tells if a Tree is a Binary Search Tree ( BST ) (Modified code)
[英]Pointers in insert function for Binary Search Tree (BST)
這個程序是一個插入 function 的二叉搜索樹,我完全理解它背后的概念和一切......我唯一不明白的是這一行:
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
聲明。 它發生在:
typedef struct _btree {...} BTreeRec , *BTree;
它將BTreeRec
聲明為struct _btree
Btree
同義詞,並將 Btree 聲明為struct _btree *
的同義詞。
所以BTree root = NULL;
相當於:
struct _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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.