streecmp/streecmp.c

88 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "streecmp.h"
int strs_cnt = 0;
struct nod *mknod(struct nod *prnt) {
if (prnt == NULL) {
return NULL;
}
prnt->pool_size++;
prnt->pool = (struct nod *) realloc(prnt->pool,
sizeof(struct nod)*prnt->pool_size);
if (prnt->pool == NULL) {
return NULL;
}
struct nod *child = &prnt->pool[prnt->pool_size-1];
child->pool_size = 0;
child->pool = NULL;
child->val.cval = 0;
child->val.ival = 0;
return child;
}
int mkstr(struct nod *rot, char *str) {
for (int i = 0; i < rot->pool_size; i++) {
struct nod *child = &rot->pool[i];
if (child->val.cval != *str) {
continue;
}
return mkstr(child, str+1);
}
struct nod *new = mknod(rot);
if (new == NULL) {
return -1;
}
new->val.cval = *str;
if (*str != '\0') {
return mkstr(new, str+1);
}
strs_cnt++;
new->val.ival = strs_cnt;
return strs_cnt;
}
int gentree(struct nod *rot, char *strs) {
char *strs_cpy = strdup(strs);
if (strs_cpy == NULL) {
return -1;
}
for (char *tok = strtok(strs_cpy, "\n"); tok != NULL; tok
= strtok(NULL, "\n")) {
int ret = mkstr(rot,tok);
if (ret < 0) {
return -1;
}
}
return 0;
}
int streecmp(struct nod *rot, char *str) {
for (int i = 0; i < rot->pool_size; i++) {
struct nod *child = &rot->pool[i];
if (child->val.cval != *str) {
continue;
}
if (child->val.cval == '\0') {
return child->val.ival;
}
return streecmp(child, str+1);
}
return 0;
}