数据结构实验之栈与队列二:一般算术表达式转换成后缀式
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Sample Input
ab+(c-d/e)f#
Sample Output
abcde/-f+
Hint
Source
/******
若为左括号直接入栈
若为右括号输出左括号之前的所有符号,然后删除左括号
若为‘+’,‘-’,‘*’,‘/’,输出栈中优先级大于等于他们的左右符号直到遇到左括号或者栈空。然后再把改符号进栈。
*******/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef char elemtype;
#define max 10000
typedef struct st
{
elemtype*top,*base;
int stacksize;
}sqstack;
void creat(sqstack*s)
{
s->base=(elemtype*)malloc(max*sizeof(elemtype));
s->top=s->base;
s->stacksize=max;
}
void push(sqstack*s,char e)
{
s->top++;
*s->top=e;
}
void pop(sqstack*s)
{
printf("%c",*s->top--);
}
int empty(sqstack*s)
{
if(s->top == s->base)
return 0;
else
return 1;
}
int main()
{
char l[1000];
sqstack s;
creat(&s);
scanf("%s",l);
for(int i=0;l[i]!='#';i++)
{
if(l[i] >='a'&&l[i]<= 'z')
printf("%c",l[i]);
else
if(l[i] == '(')
push(&s,l[i]);
else
if(l[i] == ')')
{
while(*s.top!='(')
{
pop(&s);
}
s.top--;
}
else
if(l[i] == '+'||l[i] == '-')
{
while(empty(&s)&&*s.top!='(')
pop(&s);
push(&s,l[i]);
}
else
if(l[i] == '*'||l[i] == '/')
{
while(empty(&s)&&*s.top!='('&&(*s.top == '*'||*s.top == '/'))
pop(&s);
push(&s,l[i]);
}
}
while(s.base!= s.top)
{
pop(&s);
}
printf("\n");
return 0;
}