-
Notifications
You must be signed in to change notification settings - Fork 0
/
wtree.c
112 lines (94 loc) · 2.1 KB
/
wtree.c
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* tree to count words */
#include "stdio.h"
#include "stdlib.h"
#include "ctype.h"
#include "string.h"
#define LENWORD 100
struct tnode {
char *word;
int count;
struct tnode *left;
struct tnode *right;
};
int getword(char *word);
int getch(void);
void ungetch(int c);
void error(const char *msg);
struct tnode *addtree(struct tnode *node, const char *word);
char *stralloc(const char *str);
void treeprint(struct tnode *node);
int main(void) {
char word[LENWORD];
struct tnode *root;
root = NULL;
while (getword(word) > 0)
root = addtree(root, word);
treeprint(root);
return 0;
}
/* return word length */
int getword(char *word) {
int c;
char *wordp;
wordp = word;
while ((c=getch()) != EOF)
if (isalpha(c)) {
ungetch(c);
while ((c=getch()) != EOF && isalpha(c))
*word++ = c;
*word = '\0';
ungetch(c);
break;
}
return word - wordp; // 0 no word but EOF is encountered
}
#define SIZESTKCH 1000
int stkch[SIZESTKCH];
int pstkch;
int getch(void) {
return pstkch ? stkch[--pstkch] : getchar();
}
void ungetch(int c) {
if (pstkch < SIZESTKCH)
stkch[pstkch++] = c;
else
error("no more stack space for ungetch.");
}
void error(const char *msg) {
printf("error: %s\n", msg);
exit(1);
}
struct tnode *addtree(struct tnode *node, const char *word) {
int cond;
if (node == NULL) {
node = (struct tnode *)malloc(sizeof(struct tnode));
node->word = stralloc(word);
node->count = 1;
node->right = NULL;
node->left = NULL;
} else {
/* save smaller word to left */
if ((cond=strcmp(node->word, word)) > 0)
node->left = addtree(node->left, word);
/* save greater word to right */
else if (cond < 0)
node->right = addtree(node->right, word);
else
node->count++; // same word
}
return node;
}
char *stralloc(const char *str) {
char *p;
p = malloc(strlen(str)+1);
if (p)
strcpy(p, str);
return p;
}
void treeprint(struct tnode *node) {
if (node) {
treeprint(node->left);
printf("%4d %s\n", node->count, node->word);
treeprint(node->right);
}
}