中缀表达式求值
#include <stdio.h>
#include<stdlib.h>
void main()
{
int isp(char ch);
int icp(char ch);
int isOperator(char ch);
int compute(int a,char ch,int b);
int OPND[5];int top1=-1;
char OPTR[5];int top2=-1;
OPTR[++top2]='#';
char ch1,ch2,c;
int i,j,v,a,b;
ch1=getchar();
while(ch1!='#'||OPTR[top2]!='#')
{
if(!(isOperator(ch1)))
OPND[++top1]=(int)(ch1-48);
else
{
ch2=OPTR[top2];
i=isp(ch2);
j=icp(ch1);
if(i<j)OPTR[++top2]=ch1;
else
{
ch2=OPTR[top2--];
if(ch2!='('&&i==j||i>j)
{
b=OPND[top1--];
a=OPND[top1--];
OPND[++top1]=compute(a,ch2,b);
continue;
}
}
}
ch1=getchar();
if(ch1=='#')c=getchar();
}
v=OPND[top1--];
printf("%d\n",v);
}
int isp(char ch)
{
switch(ch)
{
case ')':return 4;break;
case '*':return 3;
case '/':return 3;break;
case '+':return 2;
case '-':return 2;break;
case '(':return 1;break;
case '#':return 0;break;
default:break;
}
}
int icp(char ch)
{
switch(ch)
{
case ')':return 1;break;
case '*':return 3;
case '/':return 3;break;
case '+':return 2;
case '-':return 2;break;
case '(':return 4;break;
case '#':return 0;break;
default:break;
}
}
int isOperator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#')return 1;
else return 0;
}
int compute(int a,char ch,int b)
{
switch(ch)
{
case '+':return a+b;break;
case '-':return a-b;break;
case '*':return a*b;break;
case '/':return a/b;break;
default:break;
}
}
中缀转后缀
#include <stdio.h>
#include<stdlib.h>
#define N 10
void main()
{
int isp(char ch);
int icp(char ch);
int isOperator(char ch);
int compute(int a,char ch,int b);
char OPTR[N];int top=-1;
OPTR[++top]='#';
char ch1,ch2,c;
int i,j,v,a,b;
ch1=getchar();
while(ch1!='#'||OPTR[top]!='#')
{
if(!(isOperator(ch1)))
printf("%c ",ch1);
else
{
ch2=OPTR[top];
i=isp(ch2);
j=icp(ch1);
if(i<j)OPTR[++top]=ch1;
else
{
ch2=OPTR[top--];
if(ch2!='('&&i==j||i>j)
{
printf("%c ",ch2);
continue;
}
}
}
ch1=getchar();
if(ch1=='#')c=getchar();
}
printf("\n");
}
int isp(char ch)
{
switch(ch)
{
case ')':return 4;break;
case '*':return 3;
case '/':return 3;break;
case '+':return 2;
case '-':return 2;break;
case '(':return 1;break;
case '#':return 0;break;
default:break;
}
}
int icp(char ch)
{
switch(ch)
{
case ')':return 1;break;
case '*':return 3;
case '/':return 3;break;
case '+':return 2;
case '-':return 2;break;
case '(':return 4;break;
case '#':return 0;break;
default:break;
}
}
int isOperator(char ch)
{
if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch=='('||ch==')'||ch=='#')return 1;
else return 0;
}
int compute(int a,char ch,int b)
{
switch(ch)
{
case '+':return a+b;break;
case '-':return a-b;break;
case '*':return a*b;break;
case '/':return a/b;break;
default:break;
}
}