中缀表达式转后缀表达式C++代码

本文介绍了一个使用栈实现的算法,用于将中缀表达式转换为后缀表达式,并通过另一个栈来计算后缀表达式的值。文章包含完整的C++代码示例,演示了如何输入一个中缀表达式并输出其对应的后缀形式及其计算结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. //MyStack.h  
  2.   
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. template <class ElemType> class MyStack  
  7. {  
  8. public:  
  9.     const static  int MAXSIZE =100;  
  10.     ElemType data[MAXSIZE];  
  11.     int top;  
  12.   
  13. public:  
  14.     void init();            // 初始化栈  
  15.     bool empty();           // 判断栈是否为空  
  16.     ElemType gettop();      // 读取栈顶元素(不出栈)  
  17.     void push(ElemType x);  // 进栈  
  18.     ElemType pop();         // 出栈  
  19. };  
  20.   
  21.   
  22. template<class T> void MyStack<T>::init()  
  23. {  
  24.     this->top = 0;  
  25. }  
  26.   
  27. template<class T> bool MyStack<T>::empty()  
  28. {  
  29.     return this->top == 0? true : false;  
  30. }  
  31.   
  32. template<class T> T MyStack<T>::gettop()  
  33. {  
  34.     if(empty())  
  35.     {  
  36.         cout << "栈为空!\n";  
  37.         exit(1);  
  38.     }  
  39.     return this->data[this->top-1];  
  40. }  
  41.   
  42. template<class T> void MyStack<T>::push(T x)  
  43. {  
  44.     if(this->top == MAXSIZE)  
  45.     {  
  46.         cout << "栈已满!\n";  
  47.         exit(1);  
  48.     }  
  49.     this->data[this->top] =x;  
  50.     this->top ++;  
  51. }  
  52.   
  53. template<class T> T MyStack<T>::pop()  
  54. {  
  55.     if(this->empty())  
  56.     {  
  57.         cout << "栈为空! \n";  
  58.         exit(1);  
  59.     }  
  60.   
  61.     T e =this->data[this->top-1];  
  62.     this->top --;  
  63.     return e;  
  64. }  


  1. // PrefixToPostfix.h  
  2.   
  3. #include <vector>  
  4. using namespace std;  
  5.   
  6. bool isoperator(char op);                         // 判断是否为运算符  
  7. int priority(char op);                            // 求运算符优先级  
  8. void postfix(char pre[] , char post[],int &n);    // 把中缀表达式转换为后缀表达式  
  9. double read_number(char str[],int *i);            // 将数字字符串转变成相应的数字  
  10. double postfix_value(char post[]);                // 由后缀表达式字符串计算相应的中值表达式的值    

  1. // PrefixToPostfix.cpp  
  2.   
  3. #include "MyStack.h"  
  4. #include "PrefixToPostfix.h"  
  5.   
  6. #include <iostream>  
  7. using namespace std;  
  8.   
  9. void main()  
  10. {  
  11.     MyStack<int> stack ;  
  12.     stack.init();  
  13.   
  14.     //char pre[] ="22/(5*2+1)#";  
  15.     char exp[100];  
  16.     cout << "输入表达式(中缀,以#结束):";  
  17.     cin >> exp;  
  18.   
  19.     char post[100] ;  
  20.     //cout <<"中缀表达式为:"<< pre << endl;  
  21.   
  22.     int n =0;           // 返回后缀表达式的长度  
  23.     postfix(exp,post,n);  
  24.     cout <<"后缀表达式为:";  
  25.     forint i =0 ;i < n ;i++)  
  26.         cout << post[i] ;  
  27.   
  28.     cout << "\n由后缀表达式计算出的数值结果:  ";  
  29.     cout << postfix_value(post) << endl;  
  30.   
  31.     system("pause");  
  32. }  
  33.   
  34. bool isoperator(char op)  
  35. {  
  36.     switch(op)  
  37.     {  
  38.     case '+':  
  39.     case '-':  
  40.     case '*':  
  41.     case '/':  
  42.         return 1;  
  43.     default :   
  44.         return 0;  
  45.     }  
  46. }  
  47.   
  48.   
  49. int priority(char op)  
  50. {  
  51.     switch(op)  
  52.     {  
  53.     case '#':  
  54.         return -1;  
  55.     case '(':  
  56.         return 0;  
  57.     case '+':  
  58.     case '-':  
  59.         return 1;  
  60.     case '*':  
  61.     case '/':  
  62.         return 2;  
  63.     default :  
  64.         return -1;  
  65.     }  
  66. }  
  67.   
  68. //   把中缀表达式转换为后缀表达式,返回后缀表达式的长度(包括空格)  
  69. void postfix(char pre[] ,char post[],int &n)  
  70. {  
  71.     int i = 0 ,j=0;  
  72.     MyStack<char> stack;  
  73.     stack.init();       // 初始化存储操作符的栈  
  74.   
  75.     stack.push('#');    // 首先把结束标志‘#’放入栈底  
  76.   
  77.     while(pre[i]!='#')  
  78.     {  
  79.         if((pre[i]>='0' && pre[i] <='9')||pre[i] =='.'// 遇到数字和小数点直接写入后缀表达式  
  80.         {  
  81.             post[j++] = pre[i];  
  82.             n++;  
  83.         }  
  84.         else if (pre[i]=='(')   // 遇到“(”不用比较直接入栈  
  85.             stack.push(pre[i]);  
  86.         else if(pre[i] ==')')  // 遇到右括号将其对应左括号后的操作符(操作符栈中的)全部写入后缀表达式  
  87.         {  
  88.             while(stack.gettop()!='(')  
  89.             {  
  90.                 post[j++] = stack.pop();  
  91.                 n++;  
  92.             }  
  93.             stack.pop(); // 将“(”出栈,后缀表达式中不含小括号  
  94.         }  
  95.         else if (isoperator(pre[i]))  
  96.         {  
  97.             post[j++] = ' '// 用空格分开操作数(  
  98.             n++;  
  99.             while(priority(pre[i]) <= priority(stack.gettop()))   
  100.             {  
  101.                 // 当前的操作符小于等于栈顶操作符的优先级时,将栈顶操作符写入到后缀表达式,重复此过程  
  102.                 post[j++] = stack.pop();  
  103.                 n++;  
  104.             }  
  105.   
  106.             stack.push(pre[i]); // 当前操作符优先级大于栈顶操作符的优先级,将该操作符入栈  
  107.         }  
  108.   
  109.         i++;  
  110.     }  
  111.     while(stack.top) // 将所有的操作符加入后缀表达式  
  112.     {  
  113.         post[j++] = stack.pop();  
  114.         n++;  
  115.     }  
  116. }  
  117.   
  118. double read_number(char str[],int *i)  
  119. {  
  120.     double x=0.0;  
  121.     int k = 0;  
  122.     while(str[*i] >='0' && str[*i]<='9')  // 处理整数部分  
  123.     {  
  124.         x = x*10+(str[*i]-'0');  
  125.         (*i)++;  
  126.     }  
  127.   
  128.     if(str[*i]=='.'// 处理小数部分  
  129.     {  
  130.         (*i)++;  
  131.         while(str[*i] >= '0'&&str[*i] <='9')  
  132.         {  
  133.             x = x * 10 + (str[*i]-'0');  
  134.             (*i)++;  
  135.             k++;  
  136.         }  
  137.     }  
  138.     while(k!=0)  
  139.     {  
  140.         x /= 10.0;  
  141.         k--;  
  142.     }  
  143.   
  144.     return x;  
  145. }  
  146.   
  147. double postfix_value(char post[])  
  148. {  
  149.     MyStack<double> stack;    // 操作数栈  
  150.     stack.init();  
  151.   
  152.     int i=0 ;  
  153.     double x1,x2;  
  154.   
  155.     while(post[i] !='#')  
  156.     {  
  157.         if(post[i] >='0' && post[i] <='9')  
  158.             stack.push(read_number(post,&i));  
  159.         else if(post[i] == ' ')  
  160.             i++;  
  161.         else if (post[i] =='+')  
  162.         {  
  163.             x2 = stack.pop();  
  164.             x1 = stack.pop();  
  165.             stack.push(x1+x2);  
  166.             i++;  
  167.         }  
  168.         else if (post[i] =='-')  
  169.         {  
  170.             x2 = stack.pop();  
  171.             x1 = stack.pop();  
  172.             stack.push(x1-x2);  
  173.             i++;  
  174.         }  
  175.         else if (post[i] =='*')  
  176.         {  
  177.             x2 = stack.pop();  
  178.             x1 = stack.pop();  
  179.             stack.push(x1*x2);  
  180.             i++;  
  181.         }  
  182.         else if (post[i] =='/')  
  183.         {  
  184.             x2 = stack.pop();  
  185.             x1 = stack.pop();  
  186.             stack.push(x1/x2);  
  187.             i++;  
  188.         }  
  189.     }  
  190.     return stack.gettop();  
  191. }  


运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值