问题描述: 输入一个只包含个位数字的简单四则运算表达式字符串,计算该表达式的值
注: 1、表达式只含 +, -, *, /, (, ), 四则运算符
2、表达式数值只包含个位整数(0-9),且不会出现0作为除数的情况
3、要考虑加减乘除按通常四则运算规定的计算优先级
4、除法用整数除法,即仅保留除法运算结果的整数部分。比如8/3=2。输入表达式保证无0作为除数情况发生
5、输入字符串一定是符合题意合法的表达式,其中只包括数字字符和四则运算符字符,除此之外不含其它任何字符,不会出现计算溢出情况
• 要求实现函数:
int calculate(int len,char *expStr)
【输入】 int len: 字符串长度;
char *expStr: 表达式字符串;
【输出】 无
【返回】 计算结果
• 示例
1) 输入:char *expStr = “1+4*5-8/3”
函数返回:19
2) 输入:char *expStr = “8/3*3”
函数返回:6
关于后缀表达式解法可以在《大话数据结构》p104栈的应用一节了解。
具体实现代码如下:
#include <iostream>
using namespace std;
int calculate(int len,char *a);
int main()
{
int len;
char a[50] = "9+(3-1)*3+4/2";
//cin >> a;
len = int(strlen(a));
int total = calculate(len,a);
cout << total << endl;
return 0;
}
int calculate(int len,char *a)
{
//定义符号栈
struct node
{
char c;
node *next;
};
//定义存储运算数据栈
struct node1
{
int a1;
node1 *next;
};
///转后缀表达式
char *b = new char[len+1];
node *top = NULL;//用NULL判断是否是栈底
node *q,*p;
int n = 0;
for(int i=0; i<len; i++)
{
if( a[i] >= '0' && a[i] <='9')
b[n++] = a[i];
else if(a[i] == '(')
{
p = new node;
p -> c = a[i];
p -> next = top;
top = p;
}
else if(a[i] == '+' || a[i] == '-')
{
while(top != NULL)
{
if(top->c != '(')//当为+或-时,其优先级不高于栈顶符号,
//则在一个括号内或者如果没有括号就是全部范围的栈顶元素出栈
{
b[n++] = top->c;
q = top;
top = top->next;
delete q;
}
else
break;
}
//当前符号进栈
p = new node ;
p->c = a[i];
p->next = top;
top = p;
}
else if(a[i]=='*' || a[i]=='/')
{
while(top!=NULL && (top->c =='*' || top->c =='/'))//如果前面也是乘除就栈顶多个乘除出栈
{
b[n++] = top->c;
q = top;
top = top->next;
delete q;
}
//当前符号进栈
p = new node;
p->c = a[i];
p->next = top;
top = p;
}
else if(a[i]==')')
{
while(top->c != '(')
{
b[n++] = top->c;
q = top;
top = top->next;
delete q;
}
//删除‘(’,栈顶指向他的下一个
q = top;
top = top->next;
delete q;
}
}
//将剩余的全部弹出
while(top != NULL)
{
b[n++] = top->c;
q = top;
top = top->next;
delete q;
}
b[n] = '\0';
for(int i=0 ;i<n;i++)
cout << b[i] << ' ' ;
cout << endl;
///后缀表达式转换完毕【只能一位数】
///开始计算
node1 *p1, *q1;
node1 *top1 = NULL;
int num1,num2;
for(int i = 0;i<n;i++)
{
if(b[i] >= '0' && b[i] <= '9')
{
p1 = new node1;
p1->a1 = b[i]-'0';
p1->next = top1;
top1 = p1;
}
else
{
q1 = top1;
top1 = top1->next;
num1 = top1->a1;
num2 = q1->a1;
delete q1;//先删除被减/除/...数,当前top1还要存运算结果
if(b[i]=='+')
top1->a1=num1+num2;
else if(b[i]=='-')
top1->a1=num1-num2;
else if(b[i]=='*')
top1->a1=num1*num2;
else
top1->a1=num1/num2;
}
}
int t = top1->a1;
delete top1;
delete []b;
return t;
}