C++问题---逆波兰表达转换与计算问题

-------------------------------------
典型例题12:C++问题---逆波兰表达转换与计算问题;
-------------------------------------

//这里要主要的问题是求逆波兰表达式要用的栈和求值用的栈的元素类型不一样,所以要

//要在栈的设计时候考虑到这两方面的需求,设计成模板;
 1    #ifndef _STACK_H
 2     
 3    #define _STACK_H 
 4    #define STACK_INIT_SIZE 100    //初始栈的最大长度 
 5    #define STACKINCREMENT 10      //每次新增的栈的长度
 6     
 7    template <class DataType> 
 8    class stack{ 
 9    public: 
10        stack(); 
11        void push(DataType e);     //插入为e的新栈顶元素 
12        DataType pop();      //删除栈顶元素 
13        DataType gettop();   //取出栈顶元素
14        int stackEmpty();          //判断栈是否为空:空返回1 
15        ~stack();       //栈被销毁
16     
17    private: 
18        DataType *base;            //栈尾 
19        DataType *top;             //栈顶
20        int stacksize;
21    };
22     
23    /*------------  构造函数,创建一个新的空栈  ------*/
24    template <class DataType>
25    stack<DataType>::stack()
26    {
27        if(!(base=(DataType*)malloc(STACK_INIT_SIZE*sizeof(DataType)))) exit(1);
28        top=base;
29        stacksize=STACK_INIT_SIZE;
30    }
31     
32    /*--------   插入为e的新栈顶元素  ------------*/
33    template <class DataType>
34    void stack<DataType>::push(DataType e)
35    { 
36        if(top-base>=stacksize){
37            if(!(base=(DataType*)realloc(base,(stacksize+STACKINCREMENT)*sizeof(DataType)))) exit(1);
38            top=base+stacksize;
39            stacksize+=STACKINCREMENT;
40        }
41     
42        *top++=e;
43    }
44     
45    /*--------  删除栈顶元素  --------------*/
46    template <class DataType> 
47    DataType stack<DataType>::pop() 
48    {
49        if(top==base) return 0;
50        return *--top; 
51   
52    }
53     
54    /*--------  取出栈顶元素  --------------*/
55    template <class DataType>
56    DataType stack<DataType>::gettop() 
57    { 
58        if(top==base) return 0;
59        return *(top-1);
60    }
61     
62    /*-------   判断栈是否为空:空返回1  -------*/ 
63    template <class DataType>
64    int stack<DataType>::stackEmpty() 
65    { 
66        return top==base? 1:0; 
67    }
68     
69    /*-----------  销毁栈  -----------*/
70     
71    template <class DataType> 
72    stack<DataType>::~stack() 
73    {
74        free(base);
75    }
76    #endif
-------------------------------------
 1    #include <iostream>
 2    #include <cstdlib>
 3    #include "stack.h"
 4   
 5    using namespace std;
 6   
 7    /*
 8    **********************************
 9    *中缀->后缀 使用字符栈;
10    *后缀计算   使用浮点数栈;
11    *
12    *这两个栈元素类型不同,所
13    *以不能栈的类型无法作为全局
14    *变量来定义;
15    *
16    **********************************
17    */
18    int precedence(char op)
19    {
20        switch(op)
21            {
22            case '+':
23            case '-':
24                return 1;
25            case '*':
26            case '/':
27                return 2;
28            case '(':
29            case '@':
30            default:
31                return 0;
32            }
33    }
34    double compute(char* str)
35    {
36        stack<double> S;
37        double x,y;
38        int i = 0;
39        while (str[i])
40            {
41                if (str[i] == ' ')
42                    {
43                        i++;continue;
44                    }
45                switch (str[i])
46                    {
47                    case '+':
48                        x = S.pop()+S.pop();
49                        i++;break;
50                        break;
51                    case '-':
52                        x = S.pop();
53                        x = S.pop() - x;
54                        i++;
55                        break;
56                    case '*':
57                        x = S.pop()*S.pop();
58                        i++;
59                        break;
60                    case '/':
61                        x = S.pop ();
62                        if (x != 0.0) x =S.pop()/x;
63                        else{
64                            cerr<<"Divide by 0 !"<<endl;
65                            exit(1);
66                        }
67                        i++;
68                        break;
69                    default:
70                        x = 0.0;
71                        while (str[i]>=48 && str [i]<=57)
72                            {
73                                x = x*10.0 + str[i] -48;
74                                i++;
75                            }
76                        if(str[i] == '.'){
77                            i++;
78                            y = 0.0;
79                            double j = 10.0;
80                            while(str[i]>=48 &&str[i]<=57)
81                                {
82                                    y = y+(str[i]-48)/j;
83                                    i++;j*=10.0;
84                                }
85                            x+=y;
86                        }
87                    }
88                S.push(x);
89            }//while end;
90        if(S.stackEmpty()){
91            cerr<<"stack is empty!"<<endl;
92            exit(1);
93        }
94        x = S.pop();
95        cout<<x<<endl;
96        if(S.stackEmpty()) return x;
97        else{
98            cerr<<"expression error!"<<endl;
99            exit(1);
100        }
101    }
102   
103    void change(char* s1,char* s2)
104    {
105        stack<char> R;
106        R.push('@');
107        int i = 0,j = 0;
108        char ch =s1[i];
109        while (ch != '/0')
110            {
111                if(ch ==' ') ch = s1[++i];
112                else if(ch == '('){
113                    R.push(ch);
114                    ch = s1[++i];
115                }
116                else if (ch == ')'){
117                    while(R.gettop()!='(') s2[j++] = R.pop();
118                    R.pop();
119                    ch = s1[++i];
120                }
121                else if (ch == '+' ||ch == '-' || ch == '*' | ch == '/' ){
122                    char w = R.gettop();
123                    while (precedence(w)>=precedence(ch))
124                        {
125                            s2[j++] = w;R.pop();
126                            w = R.gettop();
127                        }
128                    R.push(ch);
129                    ch = s1[++i];
130                }
131                else{//digit and dot
132                    if ((ch<'0'||ch>'9')&&ch!='.')
133                        {
134                              cout <<" zhong zui biao da shi cuo wu!" << endl;
135                            exit(1);
136                        }
137                    while ((ch>='0' && ch <='9')||ch == '.')
138                        {
139                            s2[j++] = ch;
140                            ch = s1[++i];
141                        }
142                    s2[j++] = ' ';
143                }
144            }
145        ch = R.pop();
146        while(ch!='@'){
147            if(ch == '(')
148                {
149                    cerr<<"expression error!"<<endl;
150                    exit(1);
151                }else{
152                s2[j++] = ch;
153                ch = R.pop();
154            }
155        }
156        s2[j++] = '/0';
157    }
158   
159   
160    int main(int argc, char * argv[])
161    {
162        char a[30] = "12+(3*(12/4)-8)*6";
163        char b[30];
164        char t[30] = "10 3.5 - 4.3 2.48 +* 5 /";
165   
166        cout << "Input:"  << endl;
167        cout<<a<<endl;
168   
169        change(a,b);
170   
171        cout << "Output:" << endl;
172        cout<<b<<endl;
173   
174        cout<<compute(t)<<endl;
175        return 0;
176    }
-----------------------------
haiping@ubuntu:~/program/wy0820$ ./a.out
Input:
12+(3*(12/4)-8)*6
Output:
12 3 12 4 /*8 -6 *+
8.814
8.814
-----------------------------

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值