/* 通过使用栈将简单四则运算中缀表达式转换为后缀表达式
* '+', '-', '*', '/', '(', ')'共六种符号
* 原理:
1. 运算优先级规则是从左至右, 先乘除后加减, 有括号先算括号
2. 逐个扫描表达式, 将遇到的操作数都按原样输出, 碰到操作符时, 转3.
3. 扫描到的操作符与栈顶元素比较优先级, 栈顶元素的优先级大于等于扫描的操作符时,
栈顶操作符出栈输出, 继续重复该步骤, 直到优先级小于的条件, 将当前扫描的操作
符进栈.
4. 重复2和3步骤, 直到扫描结束, 依次将栈内操作符元素退栈到站空状态即止.
注意: 当遇到'('时, 优先级是最高的, 此时进栈, 遇到')'时, 需要退栈至'('.
*/
#include <stack>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static bool is_operator(const char c);
static int priority_compare(const char operator1, const char operator2);
//中缀表达式转后缀表达式
static void infix_express_to_suffix_express(const char *infix_express, int infix_len,
char *suffix_express, int suffix_len)
{
int i, j = 0;
std::stack<char> operator_stack;
int flag;
const char *p = infix_express;
for (i = 0; i<infix_len; ++i)
{
flag = 0;
if (!is_operator(p[i]))
{
suffix_express[j++] = p[i];
}
else
{
if (p[i] == ')')
{
while (!operator_stack.empty() && flag == 0)
{
if ('(' == operator_stack.top())
{
flag = 1;
}
else
{
suffix_express[j++] = operator_stack.top();
}
operator_stack.pop();
}
if (flag == 0)
{
printf("1. express invalid, exit. \n");
exit(-1);
}
continue;
}
else
{
while (!operator_stack.empty())
{
int priority_ret = -1;
if ((priority_ret = priority_compare(operator_stack.top(), p[i])) == -1)
{
printf("2. invalid express, exit.\n");
exit(-2);
}
if (priority_ret == 1)
{
suffix_express[j++] = operator_stack.top();
operator_stack.pop();
}
else
break;
}
operator_stack.push(p[i]);
}
}
}
while (!operator_stack.empty())
{
suffix_express[j++] = operator_stack.top();
operator_stack.pop();
}
suffix_express[j] = '\0';
}
static bool is_operator(const char c)
{
if (c == '+'
|| c == '-'
|| c == '*'
|| c == '/'
|| c == '('
|| c == ')')
return true;
return false;
}
static int priority_compare(const char operator1, const char operator2)
{
switch (operator1)
{
case '+':
case '-':
{
switch (operator2)
{
case '+':
case '-':
return 1;
break;
case '*':
case '/':
case '(':
return 0;
break;
default:
return -1;
break;
}
}
break;
case '*':
case '/':
{
switch (operator2)
{
case '+':
case '-':
case '*':
case '/':
return 1;
break;
case '(':
return 0;
break;
default:
return -1;
break;
}
}
break;
case '(':
{
switch (operator2)
{
case '+':
case '-':
case '*':
case '/':
case '(':
return 0;
default:
return -1;
break;
}
}
break;
default:
return -1;
break;
}
return -1;
}
int main(void)
{
const int MAX_EXPRESS_LENGTH = 256;
char express_infix[MAX_EXPRESS_LENGTH] = {'\0'};
char express_suffix[MAX_EXPRESS_LENGTH] = {'\0'};
printf("Input infix express('+', '-', '*', '/', '(', ')')\n");
scanf("%s", express_infix);
infix_express_to_suffix_express(express_infix, strlen(express_infix),
express_suffix, MAX_EXPRESS_LENGTH);
printf("suffix express=%s\n", express_suffix);
return 0;
}
输入:a+b*c+(d*e+f)*g
输出:suffix express=abc*+de*f+g*+