一、实验内容:
编写程序,实现中缀表达式化为后缀式输出。
已知中缀表达式中操作数全部用小写英文字母表示,运算符只含有+, -, *, /四种,定界符只有( )以及结束符#。
二、程序源代码:
运行示例:
程序源码:
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef char SElemType;
typedef struct {
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
Status InitStack(SqStack& S) {
S.base = (SElemType*)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if (!S.base) exit(0);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status Push(SqStack& S, SElemType e) { //元素e入栈
if (S.top - S.base >= S.stacksize) {
S.base = (SElemType*)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
if (!S.base) exit(1);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return 1;
}
Status Pop(SqStack& S, SElemType& e) { //删除元素e并返回
if (S.base == S.top) return 0;
e = *--S.top;
return OK;
}
Status isOperator(SElemType str) { //判断是运算符还是操作数
if (str == '+' || str == '-' || str == '*' || str == '/' || str == '(' || str == ')' || str == '#')
return 1; //是运算符返回1
else return 0; //不是运算符返回0
}
Status isStackEmpty(SqStack& S) {
if (S.base == S.top) return 1;
else return 0;
}
Status Priority(SElemType e) { //返回运算符优先级
switch (e) {
case '(':return 0; break;
case ')':return 1; break;
case '=':return 2; break;
case '+':
case '-':return 3; break;
case '*':
case '/':return 4; break;
case '**':return 5; break;
}
}
Status Gettop(SqStack& S, SElemType& e) { //得到栈顶运算符
if (S.top == S.base) return 0;
e = *(S.top - 1);
return 1;
}
void TransForm(SqStack& OPER) { //中缀表达式转后缀表达式函数
int i, j,t;
char a = ' ',b=' ',c=' ';
printf("Please input your expression:");
a = getchar();
while (a != '#') { //输入字符#结束
if (!isOperator(a)) { //输入是操作数直接输出
printf("%c", a );
}
else if (a == '(') { Push(OPER, a); } //输入字符"("直接入栈
else if (a == ')') { //输入字符"("进行元素出栈操作,直到遇到字符"("
Pop(OPER, c);
while (c != '(') {
printf("%c", c);
Pop(OPER, c);
}
}
else {
i = Priority(a);
if (i == 2 || i == 3 || i == 4 || i == 5)
{
if (isStackEmpty(OPER)) //若字符栈为空,则直接入栈
{
Push(OPER, a);
}
else { //若字符栈不为空,则返回字符栈顶端元素与输入元素比较优先级
Gettop(OPER, b);
j = Priority(b);
if (i > j) //输入元素优先级大于字符栈顶端元素,则输入元素直接入栈
Push(OPER, a);
else { //输入元素优先级小于字符栈顶端元素,则输出字符栈顶端元素,继续取字符栈下一元素比较优先级
Pop(OPER, c);
printf("%c", c);
if (!isStackEmpty(OPER)) { //如果字符栈不为空,则取字符栈顶端元素比较优先级
Gettop(OPER, c);
t = Priority(c);
while ((i < t || !isStackEmpty(OPER)) && c != '(') { //当输入元素优先级大于字符栈顶端元素优先级,则输出顶端元素,继续比较字符栈下一元素,直到优先级小于输入的元素
Pop(OPER, c);
printf("%c", c);
Gettop(OPER, c);
t = Priority(c);
}
}
Push(OPER, a);
}
}
}
}
a = getchar();
}
while (!isStackEmpty(OPER)) { //当输入完成后,依次输出字符栈剩余元素
Pop(OPER, c);
printf("%c", c);
}
}
int main()
{
SqStack Operator, Operand;
InitStack(Operator);
InitStack(Operand);
TransForm(Operator);
}