整个程序如下
#include<stdio.h>
#include <ctype.h>
#define MAXLEN 1000
#include <string.h>
#include <stdlib.h>
struct node {
int biaozhi;
char *p;
struct node *zuo;
struct node *you;
};
int shuzhuangfuzhi(struct node *, char *word,int weizhi);//返回一个正负数,正负号表示大于或小于,位数表示具体在哪一位出现的不相等
int getword(char *word, int lim);
int bijiao(char *p, char *q);
int bijiao1(char *p[], char *q);
void printree(struct node *);
int main(int argc, char *argv[])
{
struct node *p=NULL;
char *duizhao[] = { "void", "int", "char", "float", "double", "unsigned", "signed",NULL };
int weishu,a=0,b=0,c=0;
if (argc == 1)weishu = 6;
else if (argc > 2)printf("wrong use \n");
else {
++argv;
while ((a = *(*argv)++) != ' ')
if (a<'0'&&a>'9')
{ printf("wrong usage");
return -1;
}
else b = b * 10 + a - '0';
weishu = b;
}
char word[MAXLEN];
while (getword(word, MAXLEN) != EOF)
{
if (bijiao1(duizhao, word) == 0)
{
while ((c = getword(word, MAXLEN) )!= ';'&& bijiao1(duizhao, word) != 0)
if (isalpha(c))
p=shuzhuangfuzhi(p, word, weishu);
}
}
printree(p);
system("pause");
}
void printree(struct node *p)
{
if (p != NULL)
printree(p->zuo);
if (p->biaozhi==1)
printf("\n%s ", p->p);
else printf("%s ", p->p);
if (p->you!=NULL)
printree(p->you);
}
struct node *talloc(void);
char *strup(char *);
int shuzhuangfuzhi(struct node *p, char *word,int weizhi)
{
int a;
if (p == NULL)
{
p = talloc();
p->biaozhi = 0;
p->p = strup(word);
p->zuo = NULL;
p->you = NULL;
}
else if ((a = bijiao(p->p, word)) > 0)
{
if (a > weizhi)p->biaozhi = 0;
else p->biaozhi = 1;
shuzhuangfuzhi(p->zuo, word, weizhi);
}
else if (a < 0)
{
if (a > weizhi)p->biaozhi = 0;
else p->biaozhi = 1;
shuzhuangfuzhi(p->you, word, weizhi);
}
return p;
}
int bijiao(char *p, char *q)
{
int a=0;
while (*(p + a) == *(q + a) && *(p + a)!='\0')
a++;
a += 1;
if (*(p + a) == *(q + a))
return 0;
if (*(p + a) > *(q + a))
return a;
if (*(p + a) < *(q + a))
return -a;
}
int bijiao1(char *p[], char *q)
{
while (*p != NULL)
{
if (strcmp(*p++, q) == 0)
return 0;
}
return -1;
}
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w = word;
while (isspace(c = getch()));
if (c != EOF)
*w++ = c;
if (!isalpha(c))
{
*w = '\0';
return c;
}
for (; --lim > 0;w++)
if (!isalnum(*w = getch()))
{
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}
#define BUFSIZE 10000
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch:too many");
else
buf[bufp++] = c;
}
struct node *talloc(void)
{
return (struct node *) malloc(sizeof(struct node));
}
char *strup(char *s)
{
char *p;
p = (char *)malloc(strlen(s) + 1);
if (p!= NULL)
strcpy_s(p,50,s);
return p;
}