0

我尝试将 if 条件设置为 while 循环以从括号中的堆栈中删除多个运算符时 (f+g/h) 这里输出应该是 (fgh/+) 但我无法使用 while 循环运行代码我的输出是由于 if 条件而出现(fgh/),我如何在没有 SIGSEGV 的情况下放置 while 循环,我得到运行时错误 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;
}
4

0 回答 0