//计算表达式
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#define MAX_SIZE 128
struct OP
{
int type;//0
union{char symbol;double val;}value;//联合,共用体,公用体
}op_deque[MAX_SIZE];//
char symbol[MAX_SIZE];
unsigned stack_index=0,deque_index=0;
//获取栈中元素的个数
int stack_size()
{
return stack_index;
}
//压栈 把元素放入栈中
void push(char op)
{
symbol[stack_index
++]=op;
}
//弹栈 把栈顶元素弹出/删除
void pop()
{
if(stack_size()==0)
{
printf("栈是空的!不能弹出栈顶元素了\n");
return;
}
--stack_index;
}
//查看栈顶元素
char top()
{
if(stack_size()==0)
{
printf("栈是空的!,不能查看!\n");
return 0;
}
return symbol[stack_index-1];//返回栈顶元素
}
//获取字符串中的数值部分
int get_value(const char *str,double *pval)
{
int len=0;//数值的长度
char tmp[128]={0};
while(*str)
{
if(isdigit(*str)||*str=='.')
tmp[len++]=*str++;
else
break;
}
*pval=atof(tmp);
return len;
}
//解析字符串
void parse(const char *str)
{
double val;//用于保存数值
char ch;//用于保存我们的操作符
int len;//数值的长度
while(ch=*str)
{
if(ch==' ')//忽略空格
{
++str;
continue;
}
if(isdigit(ch))//如果是数字
{
len=get_value(str,&val);
op_deque[deque_index].type =1;//0表示操作数
op_deque[deque_index].value.val =val;
++deque_index;//队列的索引加1
}
else//是操作符
{
if(stack_size()==0||ch=='(')//如果是栈空或遇到了左括号
push(ch);
else
{
switch(ch)
{
case '+':
case '-':
//如果当前的运算符级别比栈顶的运算符的级
//别低就把栈顶的运算符取出放入队列中
while(stack_size()&&top()!='(')
{
op_deque[deque_index].type =0;//0表示操作符
op_deque[deque_index].value.symbol =top();
++deque_index;//队列的索引加1
pop();//弹出栈顶元素
}
push(ch);//压入栈中
break;
case '*':
case '/':
while(stack_size()&&(top()!='('||top()=='/'))
{
op_deque[deque_index].type =0;//0表示操作符
op_deque[deque_index].value.symbol =top();
++deque_index;//队列的索引加1
pop();//弹出栈顶元素
}
push(ch);//压入栈中
break;
case ')':
while(top()!='(')
{
op_deque[deque_index].type =0;//0表示操作符
op_deque[deque_index].value.symbol =top();
++deque_index;//队列的索引加1
pop();//弹出栈顶元素
}
break;
}
}
}
}
}
int main()
{
char *expression="9.232+(0.3-0.81)*233+180/7.3";
unsigned i;
parse(expression);
printf("中缀表达式:%s\n",expression);
printf("后缀表达式:");
for(i=0;i<deque_index;++i)
{
if(op_deque[i].type==1)
printf("%g",op_deque[i].value.val);
else
printf("%c",op_deque[i].value.symbol);
}
return 0;
}