samedi 27 octobre 2018

Application of stack

I am working on the problem of converting infix to postfix expression using stack. But I am getting segmentation fault error. I am not getting where am I trying to access the illegal memory?

I suspect if the stack STL container is causing some problem in pushing characters into it beyond a limit due to size restriction but I already have very few entries.

My code:

#include <iostream>
using namespace std;
#include <stack>
int isoperand(char ch)
{
  return (ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z');
}
int prec(char ch)
{
   if(ch=='^')
   {return 3;}
   if(ch=='+'||ch=='-')
   {return 2;}
   if(ch=='*'||ch=='/')
   {return 1; }
   return -1;
}
void infixTopostfix(char arr[21])
{stack <char> s;
    for(int p=0;p<21;p++)
    {
        if(isoperand(arr[p]))
        {
            cout<<arr[p];
        }
        else
        {
            if(arr[p]=='(')
            {
                s.push('(');
            }
            if(prec(arr[p])>prec(s.top()))
            {
                s.push('arr[p]');
            }
            if(arr[p]==')')
            {
                while(s.top()!='(')
                {cout<<s.top();
                    s.pop();
                }
            }
            if(prec(arr[p])<=prec(s.top()))
            {
                while(prec(s.top())>=prec(arr[p]))
                {cout<<s.top();
                    s.pop();
                }
            }

        }
    }
    while(!s.empty())
    {
        cout<<s.top();
        s.pop();
    }
}
int main()
{

    char arr[21]={'a','+','b','*','(','c','^','d','-','e',')','^','(','f','+','g','*','h',')','-','i'};
    infixTopostfix(arr);
}

Aucun commentaire:

Enregistrer un commentaire