后缀表达式的值
如果是0~9的个位数的话,遇到数字进栈,遇到符号弹出栈顶和次栈顶,运算后入栈
Eg:
1 2 3 + 6 – 2 9 * + *
从左到右遍历,a[0]是数字1,入栈,a[1]a[2],是数字,入栈
栈内:1,2,3
a[3]+是符号弹出栈顶和次栈顶,相加
栈内:1
2+3=5
入栈
栈内:1,5
6是数字,入栈
栈内:1,5,6
-是符号,弹出栈顶和次栈顶(减法除法时,次栈顶运算栈顶)
6-5=1
栈内:1,1
2,数字入栈9入栈
栈内:1,1,2,9
*弹出栈顶和次栈顶:
2*9=18
栈内:1,1,18
1+18=19
栈内:1,19
1+19=20
栈内:20
结果:20
栈:
1
1 2
1 2 3
1 5
1 5 6
1 1
1 1 2
1 1 2 9
1 1 18
1 19
20
代码:
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack <long long> s;
int main()
{
string a;
long long t=-1,m,n,ans,i=0;//2^64
getline(cin,a);
while (a[i]!=64)
{
if (a[i]>=48&& a[i]<=57)
{
if (t==-1)
{
t=a[i]-48;
s.push(t);
}
else
{
t = s.top();
s.pop();
t = t * 10 + (a[i] - '0');
s.push(t);
}
}
if (a[i]==32) t = -1;
if (a[i]==43)
{
m=s.top();
s.pop();
n=s.top();
s.pop();
ans = m + n;
s.push(ans);//压入运算结果
}
if (a[i]==45)//是减号
{
m = s.top();
s.pop();
n = s.top();
s.pop();
ans = n-m;
s.push(ans);
//同上
}
if (a[i]==42)//是乘号
{
m = s.top();
s.pop();
n = s.top();
s.pop();
ans = n*m;
s.push(ans);
//同上
}
if (a[i]==47)//是除号
{
m = s.top();
s.pop();
n = s.top();
s.pop();
ans = n/m;//次栈顶/栈顶
s.push(ans);
//同上
}
i++;
}
cout<<s.top();//栈里最后一个
return 0;
}