这是一个简单的中缀表达式求值代码,数字均为个位数,运算符+,-,*,/,不考虑语法错误
#include<stdio.h>
#include<stdlib.h>
#define INITSIZE 100
#define INCREMENT 10
typedef struct stack
{
char *base;
char *top;
int stack_size;
};
int init_stack (struct stack *s)
{
s->base=(char *)malloc((INITSIZE)*sizeof(char));
if(!s->base)
{
printf("error\n");
return 0;
}
s->top=s->base;
s->stack_size=INITSIZE;
return 1;
}
int push(struct stack *s,char e)
{
if(s->top-s->base==s->stack_size)
{
s->base=(char *)realloc(s->base,(s->stack_size+INCREMENT)*sizeof(char));
if(!s->base)
{
printf("error\n");
return 0;
}
s->top=s->base+s->stack_size;
s->stack_size+=INCREMENT;
}
*(s->top++)=e;
//printf("%d\n",*(--s->top));
return 1;
}
char pop(struct stack *s)
{
char e;
if(s->top==s->base)
{
//printf("empty\n");
return 0;
}
e=*(--s->top);
//printf("%c\n",e);
return e;
}
void main()
{
struct stack *s1,*s2;
char s[100],sign1,sign2,sign,num1,num2,sum;
int length,i;
init_stack(s1);
init_stack(s2);
printf("please input :(length less than 100)\n");
printf("';'means end\n");
gets(s);
length=strlen(s);
for(i=0;i<=length-1;i++)
{
if(s[i]<='9'&&s[i]>='0')
push(s1,(char)(s[i]-48));
else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{
sign1=s[i];
if(s2->top==s2->base)
push(s2,sign1);
else
{
sign2=pop(s2);
if((sign1=='+'&&sign2=='*')||(sign1=='+'&&sign2=='/')||(sign1=='-'&&sign2=='*')||(sign1=='-'&&sign2=='/')||(sign1==sign2)||(sign1=='+'&&sign2=='-')||(sign1=='-'&&sign2=='+')||(sign1=='*'&&sign2=='/')||(sign1=='/'&&sign2=='*'))
{
num1=pop(s1);
num2=pop(s1);
switch(sign2)
{
case '*':
{
sum=num1*num2;
push(s1,sum);
break;
}
case '/':
{
sum=num2/num1;
push(s1,sum);
break;
}
case '+':
{
sum=num1+num2;
push(s1,sum);
break;
}
case'-':
{
sum=num2-num1;
push(s1,sum);
break;
}
}
push(s2,sign1);
}
else
{
push(s2,sign2);
push(s2,sign1);
}
}
}
else if(s[i]==';')
{
while(s2->top!=s2->base)
{
sign=pop(s2);
num1=pop(s1);
num2=pop(s1);
switch(sign)
{
case '+':
{
sum=num1+num2;
push(s1,sum);
continue;
}
case '-':
{
sum=num2-num1;
push(s1,sum);
continue;
}
case '*':
{
sum=num1*num2;
push(s1,sum);
continue;
}
case '/':
{
sum=num2/num1;
push(s1,sum);
continue;
}
}
}
}
}
printf("sum=%d\n",*(--s1->top));
}