表达式求值栈的实现
算术表达式存在计算字符优先级的问题,例如:* 、/ 的优先级大于 ±,
使用栈,可以方便地计算出例如:1+2+3*4+5+6的值
思路
可以把1+2+3*4+5+6理解为:
先计算3 * 4
然后计算:1+2+12+5+6;
也就是说,我们将数字放入一个栈,将运算符放入一个栈,这样一来,如果新入运算符栈(成为cal)的运算符优先级低于栈顶的元素,就将数字栈(num)栈顶两个数字推出、运算、再推入
这样一来,我们得到以下代码。
#首先是建立栈的代码块
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
typedef struct stack{
int *base;
int *top;
int max_size;
}stack;
void CreateStack(stack &s)//创建栈
{
s.base=(int *)malloc(MAX_SIZE*sizeof(int));
s.top=s.base;
s.max_size = MAX_SIZE;
}
void Push(stack &s, char e)//添加元素
{
*(s.top++) = e;
}
int Pop(stack &s)//推出元素
{
int a = *(--s.top);
return a;
}
bool SEmpty(stack &s)//判断是否为空栈
{
// printf("the bool %d\n",(s.base==s.top));
return (s.base==s.top);
}
int getTop(stack &s)
{
return *(s.top-1);
}
void Destory(stack &s)
{
free(s.base);
s.top=NULL;
s.base=NULL;
}
不过多赘述
这里以只有加和乘为例
scanf("%c",&a);
while(a!='#')
{
f++;
if(a=='+'||a=='*')
{
while(a=='+'&&getTop(cal)=='*')
{
b=Pop(num);
c=Pop(num);
Push(num,b*c);
d=Pop(cal);
} //如果是高优先级执行
//这里可能有很多‘*’,例如1*2*3+4,使用while消去所有高优先级运算符
Push(cal,a);
}
else
{
a-='0';
Push(num,a);
}
scanf("%c",&a);
}
a使用int类型储存。
然后,输出时
a=0;
b=0;
c=0;
printf("result:\n");
while(!SEmpty(cal))
{
if(getTop(cal)=='+')
{
b=Pop(num);
c=Pop(num);
// printf("b:%d c:%d\n",b,c);
Push(num,b+c);
Pop(cal);
}
else
{
b=Pop(num);
c=Pop(num);
Push(num,b*c);
Pop(cal);
}//
}
printf("\n%d",getTop(num));
Destory(num);
Destory(cal);
num栈中最后剩下的元素就是所求的表达式的值。
如果遇到其他的运算符
就添加一个判断运算符优先级的函数,简单的条件判断,返回0、1、2就可以解决问题
也可以再添加一个oprate函数,执行运算符和pop的两个数字的计算。