中缀表达式转换为后缀表达式`
#include <iostream>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
#define TransFR struct TransformRNP
#define Node struct Node
typedef char ElemType;
#define STACK_INIT_SIZE 1000
#define MAXBUFFER 10
using namespace std;
TransFR
{
ElemType * top;
ElemType* base;
int StackSize;
};
//初始化栈
TransFR* InitStack(TransFR* point)
{
point->base = new ElemType(STACK_INIT_SIZE);
if (!point->base)
{
return 0;
}
point->top = point->base;
point->StackSize = STACK_INIT_SIZE;
return 0;
}
//压栈
TransFR* Push(TransFR* point, ElemType Elem)
{
if ((point->top - point->base) >= STACK_INIT_SIZE)
{
return 0;
}
else
{
*(point->top) = Elem;
point->top++;
}
return 0;
}
//出栈
TransFR* Pop(TransFR* point, ElemType* Elem)
{
if (point->base == point->top)
{
return 0;
}
else
{
*Elem = *--(point->top);
}
}
//判断栈的大小
int StackLength(TransFR point)
{
return (point.top - point.base);
}
int main()
{
TransFR stack;
char expression, element;
InitStack(&stack);
cout << "Please enter an infix expression ending with '#' key:" << endl;
cin >> expression;
while (expression!='#')
{
while (isdigit(expression))//如果是数字直接输出;
{
cout << expression;
cin >> expression;
if (!isdigit(expression))//处理连续的数字,如果下一次输入的不是数字则输出空格,如果是数字则连在一起输出;
{
cout << ' ';
}
}
if (')' == expression)//如果输入的是“)”则不断出栈,直到出栈的元素为“(”才停止,并将在“(”之前的元素输出出来;
{
if (StackLength(stack)==0)
{
cout << "Error!" << endl;
}
Pop(&stack, &element);
while ('('!=element)
{
cout << element << ' ';
Pop(&stack, &element);
}
}
else if ('+'==expression||'-'==expression)//如果输入的元素为“+”或者“-”,再判断栈是否为空,如果为空则直接将“+”或者“-”入栈,如果不为空,则先将栈顶元素出栈,如果是“(”则将“(”入栈如果不是则输出出栈元素(这里是表达“*”和“/”的优先级比“+”和“-”优先级高),最后再将“+”或“-”入栈;
{
if (StackLength(stack)==0)
{
Push(&stack, expression);
}
else
{
do
{
Pop(&stack, &element);
if ('('==element)
{
Push(&stack, element);
}
else
{
cout << element << ' ';
}
} while (StackLength(stack) && '(' != element);
Push(&stack, expression);
}
}
else if ('*' == expression || '/' == expression || '(' == expression)//如果输入的元素是“*”或者“/”或者“(”则直接入栈;
{
Push(&stack, expression);
}
else if ('#' == expression)//如果输入元素为“#”则退出当前循环;
{
break;
}
else
{
cout << "Input error!" << endl;
return -1;
}
cin >> expression;
}
while (StackLength(stack))//当循环结束时,如果栈里还有元素则全部输出;
{
Pop(&stack, &element);
cout << element << ' ';
}
//1+(2-3)*4+10/5#
}
![输入1+(2-3)*4+10/5的结果图](https://i-blog.csdnimg.cn/blog_migrate/2a1cc628c1a0f86cd6676bde7b7ad2d9.png)