
22.04.2009, 10:25
|
|
Участник форума
Регистрация: 27.11.2008
Сообщений: 161
С нами:
9185589
Репутация:
128
|
|
Код:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree_item_tag {
const char * word;
size_t count;
struct tree_item_tag *left, *right;
} tree_item_t;
/* insert keyword into tree or incrementing of word count. */
void insert(tree_item_t** first_item, const char* keyword) {
tree_item_t** pcur = first_item; /* pointer on current tree item */
int cmp_words;
while (*pcur != NULL) { /* searching for already inserted word inc count */
cmp_words = strcmp(keyword, (*pcur)->word);
if(cmp_words == 0) {
++(*pcur)->count;
return;
}
pcur=(cmp_words<0) ? &((*pcur)->left) : &((*pcur)->right);
} /* it is the first insert of this word */
*pcur = malloc( sizeof(tree_item_t) );
(*pcur)->word = strcpy( malloc( strlen(keyword) + 1) , keyword);
(*pcur)->count = 1;
(*pcur)->left = (*pcur)->right = NULL;
}
void print(tree_item_t* tree_item) {
if (tree_item == NULL) return;
print(tree_item->left);
(void)printf("%s %d\n",tree_item->word, tree_item->count);
print(tree_item->right);
}
/* Get word from STDIN and return it in WORD_BUF */
int get_word(char * buf_word, size_t buf_size) {
int c; /* current read symbol */
size_t word_len = 0;
while( (c=getchar()) != EOF) {
if(isalpha( (unsigned char) c) || (word_len > 0 && c == '\'')) {
buf_word[ word_len++ ] = (unsigned char) tolower(c);
if(word_len + 1 == buf_size) break; /* return only part of word */
} else if(word_len > 0) break; /* word can be returned */
}
if(word_len > 0) {
buf_word[ word_len ]= '\0';
return 1;
} else return 0;
}
int main(void) {
tree_item_t *first_item = NULL;
size_t buf_size = 50; /* must be bigger than 1 */
char * buf_word = malloc(buf_size);
while(get_word(buf_word, buf_size))
insert(&first_item, buf_word);
print(first_item);
return EXIT_SUCCESS;
}
Вот такой код. вобщем, из входного потока читается текст, разбивается на слова и заносится в бинарное дерево... Собственно, нужно сделать нерекурсивный вывод, шота голова уже не думает, помогите, плиз
|
|
|