dimanche 26 septembre 2021

SIGSEGV Fault in infix to postfix using stack

When I tried making if condition to while loop to remove more than one operator from stack in bracket (f+g/h) here output should be (fgh/+) but i am not able to run the code with while loop my output is coming (fgh/) due to if condition , how do I put while loop without SIGSEGV, im getting run-time error SIGSEGV ?

#include<bits/stdc++.h>
using namespace std;

class Solution
{
    public:
    //Function to convert an infix expression to a postfix expression.
    string infixToPostfix(string s)
    {
        // Your code here
        stack<char> op;
        string res;
        int i=0;
        while(i<s.length()){
            if(s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i]<='Z' ){
                res.push_back(s[i]);
                cout<<res<<" ";
            }
            else if(s[i]=='(')
                op.push(s[i]);
            else if(s[i]==')'){
                if(op.top()!='('){ //here SIGSEGV I want this in while loop not if statement
                    res.push_back(s[i]);
                    op.pop();
                    cout<<res<<" ";
                }
                op.pop();
            }
            else {
                if(op.empty())
                    op.push(s[i]);
                else if(precedence(s[i])>precedence(op.top()))
                    op.push(s[i]);
                else if(precedence(s[i])<precedence(op.top())){
                    while(precedence(s[i])<precedence(op.top())){
                        res.push_back(op.top());
                        op.pop();
                    }
                    op.push(s[i]);
                }
                else{
                    res.push_back(op.top());
                    op.pop();
                    op.push(s[i]);
                }
            }
        i++;
        }
        return res;
    }
    int precedence(char a)   //precedence function
    {
        if (a == '^')
            return 3;
        else if (a == '*' || a == '/')
            return 2;
        else if (a == '+' || a == '-')
            return 1;
        else if (a == '(' || a == ')')
            return 0;
    }
    

};

int main(){
    int t;
    t=1;
    cin.ignore(INT_MAX, '\n');
    while(t--){
        string exp;
        cin>>exp;
        Solution ob;
        cout<<ob.infixToPostfix(exp)<<endl;

    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire