首先举个例子 9+(3-1)×3+10÷2= 这是个中缀表达式
转成后缀表达 为 9 3 1 -3 *+10 2 /+
那么如何实现转化,转化完后又如何计算呢?
先讲下计算
从左到右遍历表达式的每个数字和符号,遇到数字就进栈,遇到符号,就将栈顶两个数字出栈,将两者进行运算,运算结果进栈;重复操作,直到遍历完后缀表达式,将得到最终结果。
例如: 9 3 1 -3 *+10 2 /+
1. 1 3 9 进栈(左边表示栈顶)
2.遇到 - 将栈中两元素弹出,计算结果再压入栈中 即 1 3 9 -> 2 9
3. 3 2 9
4. 6 9
5. 15
6. 10 15
7. 2 10 15
8. 5 15
9. 20
接着讲下如何转化为后缀表达式
首先定义一个s字符串用来存储后缀表达式的结果,再定义一个栈用来存储运算符
实现规则:
1. 遇到数字直接存到s字符串里面
2. 若栈顶符号优先级不比当前所指符号优先级低则输出
否则:符号入栈
3. 遇到 )则把(之前的全部存入s
4. 字符串遍历结束后,将栈中符号存入s
直接上代码
#include<bits/stdc++.h>
using namespace std;
int change(string a) //字符转整数
{
int ans=0,b=1;
for(int i=a.size()-1;i>=0;i--)
{
ans+=b*(a[i]-'0');
b*=10;
}
return ans;
}
int main()
{
string p; //多项式
string s; //储存后缀表达式
stack<char> q; //储存运算符号
getline(cin,p);
for(int i=0;i<p.size();i++)
{
if(p[i]>='0'&&p[i]<='9')
{
if(p[i+1]>='0'&&p[i+1]<='9')
{
s+=p[i];
// cout<<"1:"<<endl;
// cout<<s<<endl;
}
else
{
s+=p[i];
s+=' ';
// cout<<"2:"<<endl;
// cout<<s<<endl;
}
}
else
{
if(p[i]==')')
{
while(q.top()!='(')
{
char a=q.top();
q.pop();
s+=a;
// cout<<"4:"<<endl;
// cout<<s<<endl;
}
q.pop();
}
else if(p[i]=='+'||p[i]=='-')
{
while(!q.empty()&&q.top()!='(')
{
char a=q.top();
q.pop();
s+=a;
// cout<<"5:"<<endl;
// cout<<s<<endl;
}
}
else if(p[i]=='*'||p[i]=='/')
{
while(!q.empty()&&q.top()!='('&&q.top()!='+'&&q.top()!='-')
{
char a=q.top();
q.pop();
s+=a;
// cout<<"6:"<<endl;
// cout<<s<<endl;
}
}
if(p[i]!=')')
{
q.push(p[i]);
}
}
}
/*cout<<s; //输出后缀表达式
while(!q.empty())
{
char a=q.top();
q.pop();
cout<<a;
}
cout<<endl;*/
while(!q.empty())
{
s+=q.top();
q.pop();
}
cout<<s<<endl;
stack<int> w;
string r;
for(int i=0;i<s.size();i++)
{
if(s[i]>='0'&&s[i]<='9')
{
r+=s[i];
if(s[i+1]<'0'||s[i+1]>'9')
{
int a=change(r);
w.push(a);
// cout<<"a="<<a<<endl;
r="";
continue;
}
}
else
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{
int x2=w.top();
w.pop();
int x1=w.top();
w.pop();
if(s[i]=='+')
{
w.push(x1+x2);
// cout<<w.top()<<endl;
}
if(s[i]=='-')
{
w.push(x1-x2);
// cout<<w.top()<<endl;
}
if(s[i]=='*')
{
w.push(x1*x2);
// cout<<w.top()<<endl;
}
if(s[i]=='/')
{
w.push(x1/x2);
// cout<<w.top()<<endl;
}
}
}
while(!w.empty())
{
cout<<w.top()<<endl;
w.pop();
}
return 0;
}