Search code examples
c++stackpostfix-notation

postfix evaluation algorithm


here is my attempt for evaluation postfix evaluation

#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;
}

but instead of answer 23 because 4*5+3=23,it gives me answer 5,as i understood,this code gives me this result because,first it checks if there is + mark for i=0,which is not,then it checks if if it is *,this is also not,so it first push 0,then it evaluates 10*0+'3'-'0',which is equal to 3,(it would be pushed in stack),for i=1,a[i] is equal to 3,so it prints 3+, second pop is undefined,so i think it is error,please help me to fix it


Solution

  • This works with a little fix:

    #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;
    }
    

    Output (ideone):

    23
    

    Now, if you remove that i--; which I added, the code will be skipping characters in a[] because of 2 increments of i, in a[i++] and for (int i = 0; i < N; i++).

    Without i--; the output is (ideone):

    9