#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define MAXN 100005
#define MAXM 1000005
int priority(const char &ch){
switch(ch){
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
default :
return 0;
}
}
string tosuffix(const string &s){//
string ret;
stack<char>st;
for(int i=0;i<s.size();i++){
if(isdigit(s[i])){
ret+=s[i];
}
else if(s[i]=='(')st.push(s[i]);
else if(s[i]==')'){
while(st.top()!='('){
//TODO
ret+=st.top();
st.pop();
}
st.pop();
}
else {
while(!st.empty()&&priority(st.top())>=priority(s[i])){
ret+=st.top(),st.pop();
}
st.push(s[i]);
}
}
while(!st.empty()){
ret+=st.top(),st.pop();
}
return ret;
}
int calcNUM( int &a, int &b,const int & symbol){
switch (symbol) {
case '+':
//TODO
return a+b;
case '-':
//TODO
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
return (int)pow(a,b);
default:
//TODO
return 0;
}
}
void print_(const string &s){
for(int i=0;i<s.size();i++){
cout<<s[i]<<" ";
}
cout<<endl;
}
void calc (const string &s){
list<int>st;
print_(s);
for(int i=0;i<s.size();i++){
if(isdigit(s[i])){
st.push_back(s[i]-'0');
}
else {
int a,b;
a=st.back();
st.pop_back();
b=st.back();
st.pop_back();
st.push_back(calcNUM(b,a,s[i]));
for(list<int>::iterator it =st.begin();it!=st.end();it++)
cout<<*it<<" ";//
for(int j=i+1;j<s.size();j++){
cout<<s[j]<<" ";
}
cout<<endl;
}
}
}
int main(){
string s;
cin>>s;
calc(tosuffix(s));
return 0;
}
P1175 表达式的转换 (栈 链表
最新推荐文章于 2025-07-13 09:01:12 发布
该博客主要介绍了如何实现逆波兰表达式的计算,包括将中缀表达式转换为后缀表达式的方法,并提供了具体的C++代码实现。文章通过`tosuffix`函数展示了从中缀到后缀的转换过程,然后利用`calc`函数进行计算。博客内容涵盖了括号处理、运算符优先级以及计算逻辑。

950

被折叠的 条评论
为什么被折叠?



