本篇文章仅为自己的学习笔记
#include<bits/stdc++.h>
#include<stack>
#include<string>
using namespace std;
int judge(char a,char b)//判断符号优先级,0==same;;1==a>b;;-1==a<b;;这里少了括号的判断
{
if(a=='+'||a=='-')
{
if(b=='+'||b=='-') return 0;
else if(b=='*'||b=='/')return -1;
}
else{
if(b=='+'||b=='-')return 1;
else if(b=='*'||b=='/')return 0;
}
}
int oper(int a,int b,char temp)
{
int s;
if(temp=='-')s=b-a;
else if(temp=='+')s=a+b;
else if(temp=='*')s=a*b;
else s=b/a;
return s;
}
int main()
{
stack<int>ns;//存数字的
stack<char>os;//存符号的
string as;cin>>as;//输入式子
int l=as.length() ;
int t=0,re=0,i=0;
for(i=0;i<l;i++)
{
if(as[i]>='0'&&as[i]<='9')//还要考虑一下两位数及以上的情况 ,这里暂无
ns.push(as[i]-'0');
else if(as[i]=='+'||as[i]=='-'||as[i]=='/'||as[i]=='*')//操作数进行运算
{
int a,b;
if(os.size()&&ns.size()>=2)//至少有两个数才能进行运算
{
char temp=os.top();//
if(judge(temp,as[i])==0)//same
{
a=ns.top();ns.pop() ;//把数取出来
b=ns.top();ns.pop() ;
ns.push(oper(a,b,temp));
os.push(as[i]);
}
else if(judge(temp,as[i])==1)
{//temp>as[i]
a=ns.top();ns.pop() ;
b=ns.top() ;ns.pop() ;
ns.push(oper(a,b,temp));
os.pop() ;
os.push(as[i]);
}
else
os.push(as[i]);
}
else if(os.size() ==0) os.push(as[i]);
}
}
while(os.size()&&ns.size() !=1)
{
char temp=os.top() ;
os.pop() ;
int a=ns.top() ;ns.pop() ;
int b=ns.top() ;ns.pop() ;
ns.push(oper(a,b,temp));
}
cout<<ns.top() ;
return 0;
}