我正在尝试编写一个程序来将中缀表达式转换为后缀表达式。但我收到错误
<块引用>运行时错误:分段错误 (SIGSEGV)
我知道
<块引用>SIGSEGV 是由无效内存引用引起的错误
使用的算法
代码
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;
}
}
};
我已经尝试了很多来找出代码中的错误,但我无法弄清楚。请帮帮我。