Дерево поиска
#include <stdio.h>
#define M 30
#define N 1000
/* Structures declaration */
struct ti {
struct ti *p, *l, *r;
char name[30];
int phone;
};
/* Functions declaration */
int add (struct ti *root, char *name, int phone);
int del (struct ti *root, char name);
int find (struct ti *root, char name, int *phone);
struct ti* new_item(char *name, int phone);
/* Implementation */
struct ti* new_item(char *name, int phone) {
struct ti *x = (struct ti*) malloc(sizeof(struct ti));
x->p = x->l = x->r = NULL;
strcpy(x->name, name);
x->phone = phone;
return x;
}
int add (struct ti *root, char *name, int phone) {
int tmp;
if(root == NULL) {
fprintf(stderr, "Bad root\n");
return 0;
}
tmp = strcmp(root->name, name);
if(tmp > 0) {
if(root->r == NULL) {
struct ti *x = new_item(name, phone);
root->r = x;
x->p = root;
} else {
add(root->r, name, phone);
}
} else if(tmp < 0) {
if(root->l == NULL) {
struct ti *x = new_item(name, phone);
root->l = x;
x->p = root;
} else {
add(root->l, name, phone);
}
} else if(tmp == 0) {
fprintf(stderr, "For name '%s' replace old phone '%d' with new phone '%d'",
name, root->phone, phone);
root->phone = phone;
}
return 1;
}
/*
Implement del and find and main
...
*/