这题看到有挺多人做的,但是好像大部分都是用char做的啊……
这题用char做的话,在我看来还是挺麻烦的。所以说,我选择使用string(这可是字符串神器)。
思路嘛,就是把中缀表达式先转为后缀表达式,然后,把后缀表达式进行计算,每遇到一个操作符,将其按照常规计算完成以后,把栈内的数从底到顶输出,然后再把剩余的未处理字符串输出,就可以了。
因为要锻炼自己(懒),所以嘞,我用的栈也是STL的栈,具体使用方法可以google一下。
还有,stringstream这个东西是真的棒。
好吧,上代码吧。
#include <bits/stdc++.h>
using namespace std;
int pd(char ch)//判断优先级
{
switch(ch)
{
case '+': return 50;
case '-': return 50;
case '*': return 100;
case '/': return 100;
case '^': return 200;
case '(': return 10;
case ')': return 25;
}
}
inline string Infix_To_Suffix(string str)//中缀转后缀
{
stack<pair<char,int> > s;
stringstream ans;//这个东西是用来保存答案的
int n=str.length()-1;
for(int i=0;i<=n;++i)
{
if(isdigit(str[i]))
{
int t=str[i]-'0';
ans<<t<<' ';
}
else
{
if(str[i]=='(') s.push(make_pair('(',pd('(')));
else if(str[i]!=')')
{
int p=pd(str[i]);
while(!s.empty()&&s.top().second>=p)
{
ans<<s.top().first<<' ';
s.pop();
}
s.push(make_pair(str[i],p));
}
else
{
while(!s.empty()&&s.top().first!='(')
{
ans<<s.top().first<<' ';
s.pop();
}
s.pop();
}
}
}
while(!s.empty())
{
ans<<s.top().first<<' ';
s.pop();
}
string answer;
getline(ans,answer);
return answer;
}
int judge(char op,int a,int b)//计算
{
switch(op)
{
case '+':return a+b;
case '-':return a-b;
case '*':return a*b;
case '/':return a/b;
case '^':return pow(a,b);
}
}
void print(stack<int> a)//由于STL的stack不好从下往上访问,所以就写了个递归。
{
if(a.empty()) return;
int t=a.top();
if(!a.empty())
{
a.pop();
print(a);
}
printf("%d ",t);
}
int Calc_Suffix(string str)//后缀计算
{
stack<int> s,tmp;
int n=str.length()-1;
for(int i=0;i<=n;i++)
{
if(isdigit(str[i]))
{
int t=str[i]-'0';
s.push(t);
}
else if(str[i]!=' ')
{
int b=s.top();s.pop();
int a=s.top();s.pop();
s.push(judge(str[i],a,b));
print(s);
cout<<str.substr(i+2,n-i-1)<<endl;
}
}
}
int main()
{
string a;
cin>>a;
string b=Infix_To_Suffix(a);
cout<<b<<endl;
Calc_Suffix(b);
}