struct string_tree *add_node(struct string_tree *, struct string_node *str, int (*cmp)(struct string_node *, struct string_node *));
int normalcmp(struct string_node *, struct string_node *);
//简单的字符串比较
int normalcmp(struct string_node *n1, struct string_node *n2)
{
return strcmp (n1->string,n2->string);
}
int main(int argc, char **argv)
{
int j = 0;
for (j = 0; j < 1; j++) {
struct string_tree *root;
struct string_node str = {{"123",1},{"456",1},{"234",1},{"123",1},{"347",1},{"129",1},{"888",1}, {"568",1}, {"456",1}};
root = NULL;
int i = 0;
while (i<9) {
root = add_node(root, &str[i], normalcmp);
i ++;
}
i=0;
while (i<9){
if (str[i].tag) {
printf("&&&:%s\n", str[i].string);
}
i++;
}
}
return 0;
}
struct string_tree *add_node(struct string_tree *p, struct string_node *new, int (*cmp)(struct string_node *n1, struct string_node *n2))
{
int cmp_ret;
if (p == NULL) {
p = (struct string_tree *)calloc(1, sizeof(struct string_tree));
p->strn = (struct string_node*)calloc(1, sizeof(struct string_node));
memcpy(p->strn, new, sizeof(struct string_node));
p->left = p->right = NULL;
} else if ((cmp_ret = cmp(new, p->strn)) == 0) {
new->tag =0;
} else if (cmp_ret < 0) {
p->left = add_node(p->left, new, cmp);
} else {
p->right = add_node(p->right, new, cmp);
}
return p;
}
经过测试,自己实现的上述算法效率还可以,当然这里不该去比较效率,留下个思路即可,在没有库可用的情况下,也可以自己实现它。在现实中,特别是在软件工程中,还是使用现成的map比较好