Problem Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Sample Input
a*b+(c-d/e)*f#
Sample Output
ab*cde/-f*+
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct
{
char data[100000];
int top;
}Stack;
Stack *f;
void push(char c)
{
f->data[++f->top] = c;
}
char pop()
{
if(f->top+1)
{
char t = f->data[f->top--];
if(t != '(') cout<<t;
}
}
void init()
{
f = (Stack*)malloc(sizeof(Stack));
f->top = -1;
}
bool Empty()//栈是否为空
{
if(f->top+1) return false;
else return true;
}
bool pd(char c) //判断符号输入的优先级否大于栈顶的优先级
{
char t = f->data[f->top];
if(t == '(') return true;
switch(c)
{
case '+':
case '-':
return false;
break;
case '*':
case '/':
if(t == '+' || t == '-')
return true;
else
return false;
break;
}
}
int main()
{
init();
char c;
while(1)
{
cin>>c;
if(c == '#')
{
while(!Empty()) pop();
break;
}
else if(c == '+')
{
while(!Empty() && !pd(c)) pop();
push(c);
}
else if(c == '-')
{
while(!Empty() && !pd(c)) pop();
push(c);
}
else if(c == '*')
{
while(!Empty() && !pd(c)) pop();
push(c);
}
else if(c == '/')
{
while(!Empty() && !pd(c)) pop();
push(c);
}
else if(c == '(')
{
push(c);
}
else if(c == ')')
{
char t = f->data[f->top];
while(!Empty() && t != '(')
{
pop();
t = f->data[f->top];
}
if(!Empty()) f->top--;
}
else cout<<c;
}
cout<<endl;
free(f);
}