算法思路
将a+b+(c-d)*e 转换为后缀表达式,从左向右读取,读取到数字的时候(这里例子里面是字母),就将数字直接添加到后缀表达式中;遇到操作符时,将读取到的操作符与栈中元素进行对比,如果读取的操作符的优先级小于等于栈中的操作符,就将栈中的操作符弹出并添加到后缀表达式中,并且将读取的操作符压入栈中,否则直接将操作符压入栈中。
具体转化过程
-
读取到数字a,将数字a添加到postfixList的末端;此时postfixList=['a'] (postfixList表示后缀表达式) -
读取到操作符+ ,此时操作符栈op为空,直接将操作符压入栈中;此时栈op=['+'] (为了方便演示,使用数组表示栈) -
读取到数字b,将数字b添加到postfixList的末端;此时postfixList=['a','b'] -
读取到操作符'+' ,因为只有'(' 比'+','-' 优先级小,所以将栈op中除了'(' 所有操作符弹出,此时postfixList=['a','b','+'] ,栈op=['+'] -
读取到操作符'(' ,优先级最小,直接压入栈中,此时postfixList=['a','b','+'] ,栈op=['+','('] -
读取到数字c,将数字c添加到postfixList的末端,此时postfixList=['a','b','+','c'] -
读取到操作符'-' ,因为op栈顶元素'(' 优先级较小,直接将'-' 压入栈中,此时栈op=['+','(','-'] -
读取到数字d,将数字d添加到postfixList的末端,此时postfixList=['a','b','+','c','d'] -
读取到操作符')' ,将栈中'(' 上面所有的元素全部弹出并添加到postfixList末端,并将'(' 删除,此时postfixList=['a','b','+','c','d','-'] ,栈op=['+'] -
读取到操作符'*' ,因为'*' 比栈顶元素'+' 优先级高,所以直接压入栈中,此时栈op=['+','*'] -
读取到数字e,将数字e添加到postfixList的末端,此时postfixList=['a','b','+','c','d','-','e'] -
中缀表达式全部读取完毕,如果栈op未空,将栈op的所有元素弹出并添加到postfisList末尾,最后输出postfixList即为转化完成的后缀表达式,此时postfixList=['a','b','+','c','d','-','e','*','+'] -
所以中缀表达式a+b+(c-d)*e 转化为后缀表达式为ab+cd-e*+
代码实现
void InfixToPostfix()
{
int length, i, j=0;
LiStack op;
op = initStack();
char infixList[100],postfixList[100] = {0};;
printf("请输入中缀表达式:\n");
scanf("%s", infixList);
getchar();
length = (int) strlen(infixList);
for (i = 0; i < length; i++)
{
if (isdigit(infixList[i]))
{
postfixList[j++] = infixList[i];
}
else
{
if (infixList[i] == '(')
{
push(op, infixList[i]);
}
else if (infixList[i] == ')')
{
while (top(op) != '(')
{
postfixList[j++] = (char)pop(op);
}
pop(op);
}
else
{
if (infixList[i] == '+' || infixList[i] == '-')
{
if (stackEmpty(op))
{
push(op, infixList[i]);
}
else
{
while (!stackEmpty(op) && ((char)top(op) != '('))
{
postfixList[j++] = (char) pop(op);
}
push(op, infixList[i]);
}
}
else
{
if ((char)top (op) == '+' || (char)top (op) == '-' || (char)top (op) == '(')
{
push(op, infixList[i]);
}
else
{
postfixList[j++] = (char) pop(op);
push(op, infixList[i]);
}
}
}
}
}
while (!stackEmpty(op))
{
postfixList[j++] = (char)pop(op);
}
printf("%s\n", postfixList);
}
|