//表达式转换
int getPriority(char op)
{
if (op == '+' || op == '-')
return 0;
else
return 1;
}
//中缀转后缀
//从左往右扫描,从表达式前面开始扫描
//左括号入栈,右括号一直出栈,碰到右括号停下来
//栈顶运算符小于等于扫描到的运算符则出栈,写入表达式
void infixToPostfix(char infix[], char s2[], int &top2)
{
char s1[maxSize]; int top1 = -1;//s1辅助栈,s2是结果栈
int i = 0;
while(infix[i] != '\0')
{
if('0' <= infix[i] && infix[i] >= '9')
{
s2[++top2] = infix[i];
++i;
}
else if(infix[i] == '(')
{
s1[++top1] = infix[i];
++i;
}
else if(infix[i] == '+' ||
infix[i] == '-' ||
infix[i] == '*' ||
infix[i] == '/' )
{
if(top1 == -1 ||
s1[top1] == '(' ||
getPriority(infix[i]) > getPriority(s1[top1]))
{
s1[++top1] = infix[i];
++i;
}
else
s2[++top2] = s1[top1--];
}
else if (infix[i] == ')')
{
while(s1[top1] == '(')
s2[++top2] = s1[top1--];
--top1;
++i;
}
while(top1 != -1)
s2[++top2] == s1[top1--];
}
}
//中缀转前缀
//从右往左扫描,也就是从后开始扫描
//右括号入栈,碰到左括号停下来
//栈顶运算符小于扫描到的运算符出栈,写入表达式
void infixToPrefix(char infix[], int len, char s2[], int &top2)
{
char s1[maxSize]; int top1 = -1;//s1辅助栈,s2是结果栈
int i = len - 1;
while(i >= 0)
{
if('0' <= infix[i] && infix[i] >= '9')
{
s2[++top2] = infix[i];
--i;
}
else if(infix[i] == ')')
{
s1[++top1] = infix[i];
--i;
}
else if(infix[i] == '+' ||
infix[i] == '-' ||
infix[i] == '*' ||
infix[i] == '/' )
{
if(top1 == -1 ||
s1[top1] == ')' ||
getPriority(infix[i]) >= getPriority(s1[top1]))
{
s1[++top1] = infix[i];
--i;
}
else
s2[++top2] = s1[top1--];
}
else if (infix[i] == '(')
{
while(s1[top1] == ')')
s2[++top2] = s1[top1--];
--top1;
--i;
}
while(top1 != -1)
s2[++top2] == s1[top1--];
}
}
//后缀转前缀
//扫描到的运算符,移动到出栈2个子表达式的前面