利用二叉树实现排序感觉非常有意思,自己码代码如下:
/*****************************************************/
/******** Treenote 二叉树建立、比较、打印 **********/
/****** 功能 *******/
/* 统计输入中所有单词出现的次数,将输入的单词按顺序 */
/* 排列(用二叉树实现),然后按顺序打印单词(打印二叉树)*/
/*****************************************************/
#include <stdio.h>
#include <ctype.h> /* 函数 malloc() 分配内存 */
#include <string.h> /* 函数 isspace(), strcmp() 分配内存 */
#define Maxlen 100
struct note {
char *word;
int count;
struct note *left;
struct note *right;
};
int getword(char *word, int n);
struct note *addtree(struct note *p, char *word);
void printtree(struct note *p);
int main()
{
struct note *root = NULL;
char word[Maxlen];
while( getword(word, Maxlen) != EOF )
if( isalpha(word[0]))
root = addtree(root, word);
printtree(root);
return 0;
}
#define Maxbuf 10
static int buf[Maxbuf];
int sp = 0;
void ungetch(int c)
{
if(sp<Maxbuf) {
buf[sp++] = c;
}
else
printf("Error");
}
int getch(void)
{
return (sp>0) ? buf[--sp] : getchar();
}
int getword (char *word, int n)
{
int c;
char *w = word;
while(isspace(c = getch()))
;
if(c != EOF)
*w++ = c;
if(!isalpha(c)) {
*w = '\0';
return c;
}
while( --n ) {
if(!isalnum(*++w = getch())) {
ungetch(*w);
break;
}
}
*w = '\0';
return word[0];
}
void strcpy(char *s, char *t)
{
while(*s++ = *t++)
;
}
#include <stdlib.h>
char *strdup(char *s)
{
char *p;
p = (char *) malloc(strlen(s+1)); /* + 1 是末尾放'\0'*/
if(p != NULL)
strcpy(p, s);
return p;
}
struct note *talloc(void)
{
return (struct note *) malloc(sizeof(struct note));
}
struct note *addtree(struct note *p, char *word)
{
int cond;
if(p == NULL) {
p = talloc();
p->word = strdup(word);
p->count = 1;
p->left = p->right = NULL;
} else if((cond=strcmp(word,p->word )) == 0)
p->count++;
else if(cond >0)
p = addtree(p->right,word);
else
p = addtree(p->left,word);
return p;
}
void printtree(struct note *p)
{
if(p != NULL) {
printtree(p->left);
printf("%d\t%s\n", p->count,p->word);
printtree(p->right);
}
}