输入格式:
第一行输入后缀表达式长度n(1<=n<=25000);
第二行输入一个字符串表示后缀表达式(每个数据或者符号之间用逗号隔开,保证输入的后缀表达式合法,每个数包括中间结果保证不超过long long长整型范围)
输出格式:
输出一个整数,即后缀表达式的值。
样例1">输入样例1:
6
10,2,+
输出样例1:
12
输入样例2:
14
2,10,2,+,6,/,-
输出样例2:
0
注解:了解栈实现后缀表达式就能轻松的看懂这题;
其中容易错的是,忘记跳过逗号导致死循环;
还有就是要考虑负数。
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<string.h>
int main(){
long long size;
scanf("%lld",&size);
char str[size+10];
scanf("%s",str);
long long s1[size+10];
long long top1 = -1;
long long top2 = -1;
long long temp[1000] = {-1};
long long i = 0;
long long sign = -1;
long long temp2 = 0;
long long temp3 = 0;
int flag = 0;
while(str[i]!='\0')
{
if(str[i]==',')
{
i++;
continue;
}
else if(str[i]=='-'&&str[i+1]>='0'&&str[i+1]<='9')
{
flag = 1;
i++;
continue;
}
else if(str[i]>='0'&&str[i]<='9')
{
if(str[i+1]!='\0'&&str[i+1]!=',')
{
sign++;
temp[sign] = str[i]-'0';
i++;
}else
{
sign++;
temp[sign] = str[i]-'0';
for(long long j = 0;j<=sign;j++)
{
long long temp4 = pow(10,(double)(sign-j));
temp2 += temp4*temp[j];
}
top1++;
if(flag)
{
s1[top1] = temp2*(-1);
flag = 0;
}
else
s1[top1] = temp2;
temp2 = 0;
sign = -1;
i++;
continue;
}
}else if(str[i]=='+'||str[i]=='*'||str[i]=='/')
{
switch(str[i])
{
case '+': temp3 = s1[top1-1]+s1[top1];
s1[top1-1] = temp3;
top1--;
i++;
break;
case '*': temp3 = s1[top1-1]*s1[top1];
s1[top1-1] = temp3;
top1--;
i++;
break;
case '/': temp3 = s1[top1-1]/s1[top1];
s1[top1-1] = temp3;
top1--;
i++;
break;
}
}else if (str[i]=='-'&&flag==0)
{
temp3 = s1[top1-1]-s1[top1];
s1[top1-1] = temp3;
top1--;
i++;
}
}
printf("%lld",s1[top1]);
}