- 思路:
- 中缀表达式转后缀表达式
- 思路:(一个操作符stack和一个后缀vec)
- 从左往右遍历
- 数字直接入后缀vec
- 操作符压入操作符stack
- 操作符stack为空,任何符号压入操作符stack
- 不为空
- 左括号直接压入操作符stack
- 遇到右括号,util 操作符stack中最近的左括号全部依次出操作符stack入后缀vec
- 非括号操作符
- 优先级高于操作符stack top的操作符,入操作符stack
- 优先级不高于stack top的操作符,且stack top不为括号,循环依次出依次出操作符stack入后缀vec
- 遍历完成,操作符依次出操作符stack入后缀vec
- 例子:
-
2+9/3-5-->293/+5-
-
1+2*4*(4+1)-5/2+3-->124*41+*+52/-3+
-
1+2*4*((4+1)*3+1)-5/2+3--->124*41+3*1+*+52/-3+
-
- 思路:(一个操作符stack和一个后缀vec)
- 计算后缀表达式
- 遍历后缀表达式
- 遇到数字,入数据stack
- 遇到操作符,从数据stack出2个数据元素进行计算并将计算结果压入数据栈;继续循环
- 运算结果取栈顶元素
- 中缀表达式转后缀表达式
- 代码如下:
#include<iostream> #include<vector> #include<stack> class SimpleCal{ private: std::stack<char> mOps; std::stack<int> mDatas; std::vector<char> mInfixVec; std::vector<char> mPostfixVec; public: SimpleCal(std::vector<char> vec):mInfixVec(vec){ } bool IsPriority(char op1,char op2){ return op1 != '+' && op1 != '-' && op2 != '*' && op2 != '/'; } int CalTwoNum(char op,int a,int b){ switch (op) { case '+': return a+b; case '-': return a-b; case '*': return a*b; case '/': return a/b; } return 0; } int CalInput(){ int res = 0; InfixToPostfix(); for(auto i:mPostfixVec){ if(IsOper(i)){ int b = mDatas.top(); mDatas.pop(); int a = mDatas.top(); mDatas.pop(); int c = CalTwoNum(i,a,b); mDatas.push(c); }else{ mDatas.push(i-'0'); } } if(mDatas.empty()){ return res; }else{ return mDatas.top(); } } void InfixToPostfix(){ for(auto i:mInfixVec){ if(!IsOper(i)){ mPostfixVec.push_back(i); }else{ if(mOps.empty()){ mOps.push(i); continue; }else{ if(')' == i){ while('(' !=mOps.top()){ mPostfixVec.push_back(mOps.top()); mOps.pop(); } if('(' ==mOps.top()){ mOps.pop(); } }else if('(' == i){ mOps.push(i); }else{ if(IsPriority(i,mOps.top())){ mOps.push(i); }else{ while(!mOps.empty() && !IsPriority(i,mOps.top()) && mOps.top() != '('){ mPostfixVec.push_back(mOps.top()); mOps.pop(); } mOps.push(i); } } } } } while(!mOps.empty()){ mPostfixVec.push_back(mOps.top()); mOps.pop(); } } bool IsOper(const char a){ if ('+' == a ||'-' == a||'*' == a||'/' == a||'(' == a||')' == a){ return true; } return false; } void PrintRes(){ int res = CalInput(); std::cout<<"中缀表达式:"; for(auto i :mInfixVec){ std::cout<<i; } std::cout<<std::endl; std::cout<<"后缀表达式:"; for(auto i:mPostfixVec){ std::cout<<i; } std::cout<<std::endl; std::cout<<"result:"<<res<<std::endl; } }; int main(){ // 1+2*4*(4+1)-5/2+3 SimpleCal cal(std::vector<char>{'1','+','2','*','4','*','(','4','+','1',')','-','5','/','2','+','3'}); // 1+2*4*((4+1)*3+1)-5/2+3 // SimpleCal cal(std::vector<char>{'1','+','2','*','4','*','(','(','4','+','1',')','*','3','+','1',')','-','5','/','2','+','3'}); // 2+9/3-5 // SimpleCal cal(std::vector<char>{'2','+','9','/','3','-','5'}); cal.PrintRes(); } - 运行结果:

四则运算-c++
最新推荐文章于 2025-09-05 14:17:40 发布
本文介绍了如何使用C++实现中缀表达式转后缀表达式的方法,包括思路和详细步骤。通过遍历中缀表达式,利用栈操作将操作符和数字分别处理,遇到括号时特别处理。最后,对于后缀表达式,通过数据栈计算得出最终结果。
1178

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



