中缀表达式、后缀表达式,都是用来呈现运算表达式的一种方式。
标准表达式:4+5+(6*7)
中缀表达式,就是标准的表达式,即4+5+(6*7)
后缀表达式,符号在后的表达式,即4 5 + 6 7 *
中缀表达式 转 后缀表达式 的思想是(注意的是:只有( + - * / 这5种符号才会入栈)
1. 读到操作数时,立即输出
2. 读到的是操作符,分以下情况处理
+ 如果是 (,入栈
+ 如果是 ),弹出栈中符号,直到弹出的是 (
+ 如果是 + 或 - ,依次弹出栈中所有符号(直到栈顶是(,弹出结束),最后将+ 或 -入栈
+ 如果是 * 或 /,依次弹出栈中所有符号(直到栈顶是* 或者 /,弹出结束),最后将+ 或 -入栈
3. 如果读到结尾,栈还是不为空,则依次弹出栈中所有符号
4. 步骤2和3中所有的弹出操作,除了 ( ,都要输出显示,最后输出的结果就是后缀表达式
代码实现如下
(下面的代码有调用到一个API(profix_expression_in),这个API是跟根据后缀表达式来计算表达式的结果,详见栈的应用—(后缀表达式),另外栈的基本实现,详见栈的实现(链表方式))
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "stack.h"
bool infix_to_profix_is_number(char str)
{
if(str>='0' && str<='9')
return true;
else
return false;
}
void infix_to_profix_is_symbol(STACK * inputStack, STACK * outputStack, char str)
{
char value = 0;
if('(' == str)
{
stack_push(inputStack, str);
}
else if(')' == str)
{
while((true != stack_is_empty(inputStack)) && ('(' != stack_top(inputStack)) )
{
value = stack_pop(inputStack);
printf("%c ", value);
profix_expression_in(outputStack, &value);
}
stack_pop(inputStack); // pop ')'
}
else if('+'==str || '-'==str)
{
// pop the low or the same priority string in the Stack
while((true != stack_is_empty(inputStack)) && ('(' != stack_top(inputStack)))
{
value = stack_pop(inputStack);
printf("%c ", value);
profix_expression_in(outputStack, &value);
}
stack_push(inputStack, str);
}
else if('*'==str || '/'==str)
{
// pop the low or the same priority string in the Stack
while((true != stack_is_empty(inputStack)) && ('*'==stack_top(inputStack) || '/'==stack_top(inputStack)))
{
value = stack_pop(inputStack);
printf("%c ", value);
profix_expression_in(outputStack, &value);
}
stack_push(inputStack, str);
}
}
void infix_to_profix_read(STACK * inputStack, STACK * outputStack, char * str)
{
char *p = str;
int value = 0;
while(*p != '\0')
{
if(' ' != *p)
{
if(true == infix_to_profix_is_number(*p))
{
printf("%c ", *p);
profix_expression_in(outputStack, p);
}
else
{
infix_to_profix_is_symbol(inputStack, outputStack, *p);
}
}
p = p + 1;
}
while(true != stack_is_empty(inputStack))
{
value = stack_pop(inputStack);
printf("%c ", value);
profix_expression_in(outputStack, &value);
}
}
void infix_to_profix_main_test(void)
{
// char string[] = "1 + ( 2 - 1 ) * 3"; // profix (1 2 1 - 3 * +), result (4)
// char string[] = "1 + ( ( 2 + 3 ) * 4 ) - 5"; // profix (1 2 3 + 4 * + 5 -), result (16)
char string[] = "5 + ( 2 + 3 ) * 4 / 5"; // profix (5 2 3 + 4 * 5 / -), result (9)
// char string[] = "4 + 5 + ( 6 * 7 )"; // profix (4 5 + 6 7 * +), result (51)
STACK * inputStack = stack_init();
STACK * outputStack = stack_init();
printf("Infix is : %s\n", string);
printf("Profix is : ");
infix_to_profix_read(inputStack, outputStack, string);
printf("\ncalculate result = %d\n", stack_pop(outputStack));
}
输出效果如下