1.直接求解
遇到数字直接放入操作数栈,遇到操作符则根据规则进行操作
#include<bits/stdc++.h>
using namespace std;
unordered_map<char,int>priority{{'+',1},{'-',1},{'*',2},{'/',2}};
stack<int>num;
stack<char>op;
void eval()
{
int res=0;
int a=num.top();
num.pop();
int b=num.top();
num.pop();
char x=op.top();
op.pop();
if(x=='+')res=b+a;
if(x=='-')res=b-a;
if(x=='*')res=b*a;
if(x=='/')res=b/a;
num.push(res);
}
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i++)
{
if(isdigit(s[i]))
{
int j=i,x=0;
while(j<s.size()&&isdigit(s[j]))
{
x=10*x+s[j]-'0';
j++;
}
num.push(x);
i=j-1;
}
else if(s[i]=='(')
op.push(s[i]);
else if(s[i]==')')
{
while(op.top()!='(')
eval();
op.pop();
}
else
{
while(op.size()&&priority[op.top()]>=priority[s[i]])
eval();
op.push(s[i]);
}
}
while(op.size())eval();
cout<<num.top();
return 0;
}
2.将中缀表达式转换为后缀表达式后进行解决
(1)中缀转后缀:遇到数字直接加入后缀表达式,遇到操作符则根据规则进行操作
(2)后缀表达式求值:从左到右扫描,遇到数字入操作数栈,遇到操作符操作离它最近的两个操作数,再入栈
数字
#include<bits/stdc++.h>
using namespace std;
unordered_map<char,int>priority{{'+',1},{'-',1},{'*',2},{'/',2}};
string infixToPostfix(string infix)
{
string postfix;
stack<char>op;
for(int i=0;i<infix.size();i++)
{
if(isdigit(infix[i]))postfix+=infix[i];
else if(infix[i]=='(')op.push(infix[i]);
else if(infix[i]==')')
{
while(!op.empty()&&op.top()!='(')
{
postfix+=op.top();
op.pop();
}
if(op.empty())
return "Invalid Expression!";
op.pop();
}
else
{
if(!op.empty()&&priority[op.top()]>=priority[infix[i]])
{
postfix+=op.top();
op.pop();
}
op.push(infix[i]);
}
}
while(op.size())
{
if(op.top()=='(')
return "Invalid Expression";
postfix+=op.top();
op.pop();
}
return postfix;
}
int get(string postfix)
{
stack<int>num;
for(char x : postfix)
{
if(isdigit(x))num.push(x-'0');
else
{
int a=num.top();
num.pop();
int b=num.top();
num.pop();
if(x=='+')num.push(b+a);
if(x=='-')num.push(b-a);
if(x=='*')num.push(b*a);
if(x=='/')num.push(b/a);
}
}
return num.top();
}
int main(){
string infix;
cin>>infix;
string postfix=infixToPostfix(infix);
cout<<postfix<<endl;
cout << get(postfix) << endl;
return 0;
}
字母
#include<bits/stdc++.h>
using namespace std;
unordered_map<char,int>priority{{'+',1},{'-',1},{'*',2},{'/',2}};
string infixToPostfix(string infix)
{
string postfix;
stack<char>op;
for(int i=0;i<infix.size();i++)
{
if((infix[i]>='a'&&infix[i]<='z')||(infix[i]>='A'&&infix[i]<='Z'))
postfix+=infix[i];
else if(infix[i]=='(')op.push(infix[i]);
else if(infix[i]==')')
{
while(!op.empty()&&op.top()!='(')
{
postfix+=op.top();
op.pop();
}
if(op.empty())
return "Invalid Expression!";
op.pop();
}
else
{
if(!op.empty()&&priority[op.top()]>=priority[infix[i]])
{
postfix+=op.top();
op.pop();
}
op.push(infix[i]);
}
}
while(op.size())
{
if(op.top()=='(')
return "Invalid Expression";
postfix+=op.top();
op.pop();
}
return postfix;
}
int main(){
string infix;
cin>>infix;
string postfix=infixToPostfix(infix);
cout<<postfix<<endl;
return 0;
}