中缀表达式转为后缀表达式
背景需求
主体函数:
std::string infixToSuffix(std::string s) {
SqStack S;
std::string res;
InitStack(S);
for (auto i: s) {
// 操作数直接加入后缀表达式
if (std::isdigit(i)) {
res += i;
continue;
}
if (i != ')')
// 栈空或者操作符是(直接入栈
if (StackEmpty(S) || i == '(') {
Push(S, i);
continue;
} else {
char c1;
// 操作符是+-时的操作
if (i == '+' || i == '-') {
getTop(S, c1);
if (c1 == '(') {
Push(S, i);
continue;
}
while (Pop(S, c1)) {
res += c1;
}
Push(S, i);
} else {
// 操作符是*/时的操作
getTop(S, c1);
if (c1 == '(') {
Push(S, i);
continue;
}
while (c1 == '*' || c1 == '/') {
res += c1;
getTop(S, c1);
}
Push(S, i);
}
}
else {
char c;
while (Pop(S, c)) {
if (c != '(')
res += c;
else {
break;
}
}
}
}
char c2;
while (Pop(S, c2)) {
res += c2;
}
return res;
}
栈操作:
void InitStack(SqStack &S)
{
S.top = -1;
}
bool StackEmpty(SqStack S)
{
if (S.top == -1)
{
return true;
}
else
{
return false;
}
}
//入栈
bool Push(SqStack &S, char x)
{
// 判断栈是否满了
if (S.top == MaxSize - 1)
{
return false;
}
// 将新元素从栈顶插入
S.data[++S.top] = x;
return true;
}
bool Pop(SqStack &S, char &x)
{
// 栈空
if (StackEmpty(S))
return false;
x = S.data[S.top--];
return true;
}
bool getTop(SqStack S, char &x){
if (StackEmpty(S))
return false;
x = S.data[S.top];
return true;
}
测试:
std::string s;
std::string s1;
s = infixToSuffix("1+2*3(4-5)-6/7");
s1 = infixToSuffix("((15/(7-(1+1)))*3)-(2+(1+1))");
std::cout<<s<<std::endl;
std::cout<<s1;
输出:
12345-*+67/-
15711+-/3*211++-
我知道有改进的空间,但是我不想改了。