二叉树实现排序(C语言)

利用二叉树实现排序感觉非常有意思,自己码代码如下:

/*****************************************************/
/********   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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值