运行时错误:分段错误 (SIGSEGV)

时间:2021-04-08 15:12:28

标签: algorithm segmentation-fault stack postfix-notation infix-notation

我正在尝试编写一个程序来将中缀表达式转换为后缀表达式。但我收到错误

<块引用>

运行时错误:分段错误 (SIGSEGV)

我知道

<块引用>

SIGSEGV 是由无效内存引用引起的错误

使用的算法

  1. 从左到右扫描中缀表达式。
  2. 如果扫描的字符是操作数,则输出它。
  3. 否则, 1 如果扫描的运算符的优先级大于堆栈中运算符的优先级(或堆栈为空或堆栈包含“(”),则将其压入。 2 否则,从堆栈中弹出所有优先级大于或等于扫描运算符的运算符。这样做之后,将扫描的操作符推入堆栈。 (如果您在弹出时遇到括号,请停在那里并将扫描的运算符压入堆栈。)
  4. 如果扫描的字符是‘(’,则将其压入堆栈。
  5. 如果扫描到的字符是‘)’,则出栈并输出直到遇到‘(‘,并丢弃两个括号。
  6. 重复步骤 2-6,直到扫描到中缀表达式。
  7. 打印输出
  8. 从堆栈中弹出并输出,直到它不为空。

代码

class Solution
{
    int prec(char a)
    {
        if (a == '^')
            return 3;
        else if (a == '*' || a == '/')
            return 2;
        else if (a == '+' || a == '-')
            return 1;
        else
            return -1;
    }
public:
    string infixToPostfix(string str)
    {
        stack<char> stk;
        string ans;
        for (auto e : str)
        {
            if ((e >= 'a' && e <= 'z') || (e >= 'A' && e <= 'Z'))
                ans += e;
            else if (e == '(')
                stk.push(e);
            else if (stk.empty())
                stk.push(e);
            else if (prec(stk.top()) < prec(e))
            {
                if (e != ')')
                    stk.push(e);
                else
                {
                    while (!stk.empty() && stk.top() != '(')
                    {
                        ans = ans + stk.top();
                        stk.pop();
                    }
                    if (stk.empty())
                        continue;
                    else
                        stk.pop();
                }
            }
            else if (prec(stk.top()) >= prec(e))
            {
                while (prec(stk.top()) >= prec(e) && !stk.empty())
                {
                    if (prec(stk.top()) > prec(e))
                    {
                        ans = ans + stk.top();
                        stk.pop();
                    }
                    else
                    {
                        //same precedence so checking for associativity
                        if (stk.top() == '^') //associativity from R->L
                            stk.push(e);
                        else                //associativity from L->R
                        {
                            ans = ans + stk.top();
                            stk.pop();
                        }
                    }
                }
                stk.push(e);
            }
        }
        if (stk.empty())
            return ans;
        else
        {
            while (!stk.empty())
            {
                ans = ans + stk.top();
                stk.pop();
            }
            return ans;
        }
    }
};

我已经尝试了很多来找出代码中的错误,但我无法弄清楚。请帮帮我。

0 个答案:

没有答案