后缀评估算法

postfix evaluation algorithm

本文关键字:算法 评估 后缀      更新时间:2023-10-16

这是我对评估后缀评估的尝试

#include<iostream>
#include<string>
using namespace std;
template<class T>
class Stack
{
private:
    T *s;int N;
public:
    Stack(int maxn)
    {
        s=new T[maxn];
        N=0;
    }
    int empty()const
    {
    return N==0;
    }
    void push(T k)
    {
        s[N++]=k;
    }
    T pop()
    {
        return s[--N];
    }
    };
int main()
    {
        //postfix evaluation
        char *a="3+4*5";
        int N=strlen(a);
        Stack<int>save(N);
        for(int i=0;i<N;i++)
        {
            if(a[i]=='+')
                save.push(save.pop()+save.pop());
            if(a[i]=='*')
                save.push(save.pop()*save.pop());
            if((a[i]>='0' &&  a[i]<='9'))
                save.push(0);
            while((a[i]>='0' && a[i]<='9'))
                save.push(10*save.pop()+(a[i++]-'0'));
                    }
        cout<<save.pop()<<"  "<<endl;
    return 0;
}

但是,它给出的不是答案23,因为4*5+3=23,而是答案5,正如我所理解的,这段代码给我这个结果是因为,首先它检查i=0是否有+标记,这不是,然后它检查如果是*,这也不是,所以它首先推0,然后它计算10*0+'3'-'0',这等于3,(它将在堆栈中推),对于i=1,a[i]等于3,所以它打印3+,第二个pop是未定义的,所以我认为这是错误的,请帮助我修复

这需要一个小的修复:

#include <iostream>
#include <cstring>
using namespace std;
template<class T>
class Stack
{
private:
    T *s;
    int N;
public:
    Stack(int maxn)
    {
        s = new T[maxn];
        N = 0;
    }
    int empty()const
    {
        return N == 0;
    }
    void push(T k)
    {
        s[N++] = k;
    }
    T pop()
    {
        return s[--N];
    }
};
int main()
{
    //postfix evaluation
    const char *a = "3 4 5*+";
    int N = strlen(a);
    Stack<int>save(N);
    for (int i = 0; i < N; i++)
    {
        if (a[i]=='+')
            save.push(save.pop() + save.pop());
        if (a[i]=='*')
            save.push(save.pop() * save.pop());
        if (a[i] >= '0' && a[i] <= '9')
        {
            save.push(0);
            while (a[i] >= '0' && a[i] <= '9')
                save.push(10 * save.pop() + a[i++] - '0');
            i--;
        }
    }
    cout << save.pop() << "  " << endl;
    return 0;
}

输出(视频):

23

现在,如果删除我添加的i--;,代码将跳过a[]中的字符,因为ia[i++]for (int i = 0; i < N; i++)中有两个增量。

如果没有i--;,输出为(视频):

9