我们平时写的数学表达式都是中缀表达式,如:a+b*c+(d*e+f)*g
现在要用计算机来实现这样的表达式,可以转换成后缀表达式再进行运算。自己写了一段代码如下:
#include <iostream> #include <stack> using namespace std; void midtotail(char *a) { stack<char> c; while (*a!='\0') { if(*a >= '0' && *a <= '9') cout<<*a; else if(*a >= 'a' && *a <= 'z') cout<<*a; else { if(c.empty() || *a == '(' || *a == '*' || *a == '/') c.push(*a); else if (*a == ')') { while (c.top()!= '(') { cout<<c.top(); c.pop(); } c.pop(); } else if (*a == '+' || *a == '-') { if (c.top() != '(') { while (!c.empty() && c.top()!= '(') { cout<<c.top(); c.pop(); } } c.push(*a); } } a++; } while (!c.empty()) { cout<<c.top(); c.pop(); } } int main() { //char a[] = "a+b*c+(d*e+f)*g"; char *a = new char[30]; cout<<"请输入一个中缀表达式:"; cin>>a; cout<<"输入的中缀表达式是:"; cout<<a<<endl; cout<<"后缀表达式是:"; midtotail(a); cout<<endl; delete [] a; return 0; }原文链接:https://www.f2er.com/datastructure/383198.html