1.c
#include<stdio.h>
#define size 100
struct
{
char ch;
int pri;
}
lpri[]={{'=',0},{'(',1},{'*',5},{'/',5},{'+',3},{'-',3},{')',6}},
rpri[]={{'=',0},{'(',6},{'*',4},{'/',4},{'+',2},{'-',2},{')',1}};
int leftpri(char op)
{
int i;
for(i=0;i<7;i++)
if(lpri[i].ch==op)
return lpri[i].pri;
}
int rightpri(char op)
{
int i;
for(i=0;i<7;i++)
if(rpri[i].ch==op)
return rpri[i].pri;
}
int inop(char ch)
{
if(ch=='('||ch=='*'||ch=='/'||ch=='+'||ch=='-'||ch==')')
return 1;
else
return 0;
}
int precede(char op1,char op2)
{
if(leftpri(op1)==rightpri(op2))
return 0;
else if(leftpri(op1)<rightpri(op2))
return -1;
else
return 1;
}
void trans(char *exp,char postexp[])
{
int i=0;
struct
{
char data[size];
int top;
}op;
op.top=-1;
op.top++;
op.data[op.top]='=';
while(*exp!='\0')
{
if(!inop(*exp))
{
while(*exp>='0'&&*exp<='9')
{
postexp[i++]=*exp;
exp++;
}
postexp[i++]='#';
}
else
switch(precede(op.data[op.top],*exp))
{
case -1:
op. top++;
op.data[op.top]=*exp;
exp++;
break;
case 0:
op.top--;
exp++;
break;
case 1:
postexp[i++]=op.data[op.top];
op.top--;
break;
}
}
while(op.data[op.top]!='=')
{
postexp[i++]=op.data[op.top];
op.top--;
}
postexp[i]='\0';
}
2.c
#include<stdio.h>
#include<string.h>
#define maxsize 100
#define maxop 7
extern int leftpri(char op); //求运算符op的优先级
extern int rightpri(char op);
extern int inop(char ch); //判断ch是否为运算符
extern void trans(char *exp,char postexp[]); //将算术表达式exp转换成后缀表达式postexp
void main()
{
char exp[maxsize],postexp[maxsize];
scanf("%s",exp);
trans(exp,postexp);
printf("\n%s\n",exp);
printf("\n%s\n",postexp);
}




 

posted on 2012-03-30 11:06  C's  阅读(348)  评论(0编辑  收藏  举报