1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tree.h"
char *sneed_strdup(char *s);
struct tnode *talloc(void);
int compare(char *w, struct tnode *p, int bar, int *found);
struct tnode *naddtree(struct tnode *p, char *w, int bar, int *found)
{
int cond;
if (p == NULL) {
p = talloc();
p->word = sneed_strdup(w);
p->count = 1;
p->match = *found;
p->left = p->right = NULL;
} else if ((cond = compare(w, p, bar, found)) == 0) {
p->count++;
} else if (cond < 0) {
p->left = naddtree(p->left, w, bar, found);
} else if (cond > 0) {
p->right = naddtree(p->right, w, bar, found);
}
return p;
}
void ntreeprint(struct tnode *p)
{
if (p != NULL) {
ntreeprint(p->left);
if (p->match)
printf("%4d %s\n", p->count, p->word);
ntreeprint(p->right);
}
}
void treefree(struct tnode *p) {
if (p != NULL) {
treefree(p->left);
treefree(p->right);
free(p->word);
free(p);
}
}
struct tnode *talloc(void)
{
return (struct tnode *) malloc(sizeof(struct tnode));
}
char *sneed_strdup(char *s)
{
char *p;
p = (char *) malloc(strlen(s) + 1);
if (p != NULL)
strcpy(p, s);
return p;
}
int compare(char *w, struct tnode *p, int bar, int *found)
{
int cond;
if ((cond = strncmp(w, p->word, bar)) == 0)
if ((cond = strcmp(w + bar, p->word + bar)) != 0)
p->match = *found = YES;
return cond;
}
|