您的位置:首页 > 编程语言 > C语言/C++

实验项目3-6:表达式转换(中缀表达式转后缀表达式)

2016-07-22 21:34 393 查看
算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。

输入格式:

输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。

输出格式:

在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。

输入样例:

2+3*(7-4)+8/4

输出样例:

2 3 7 4 - * + 8 4 / +

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define MAX 25
typedef char Element;
typedef struct node
{
Element data[MAX];
int top;
}stack;
stack *Initial()
{
stack *q;
q=malloc(sizeof(stack));
q->top=-1;
return q;
}
void push(stack *p,Element item)
{
p->data[++p->top]=item;
}

Element pop(stack *p)
{
return (p->data[p->top--]);
}
int opt(char a)
{
if(a=='-'||a=='+')
return 1;
if(a=='*'||a=='/')
return 2;
}
int IsEmpty(stack *p)
{
return p->top==-1;
}
main()
{
Element s[MAX],c;
stack *q=Initial();
int flag=0,i=0,flag2=0;
scanf("%c",&c);
while(c!='\n')
{
if(flag2==0&&(c=='-'||c=='+'))
{
if(c=='-')
{
s[i++]=c;
s[i]='\0';
}
flag2=1;
}
else
{
while(isdigit(c)||c=='.')
{
flag2=1;
s[i++]=c;
s[i]='\0';
scanf("%c",&c);
if(!isdigit(c)&&c!='.')
{
if(flag==0)//第一个数字
{
printf("%s",s);
flag=1;
}
else
printf(" %s",s);
i=0;
break;
}
}
if(c=='\n')
break;
else
if(IsEmpty(q))
push(q,c);
else
{
if(c==')')
{
while(q->data[q->top]!='(')
printf(" %c",pop(q));
pop(q);
}
else if(c=='(')
{
push(q,c);
flag2=0;
}
else if(opt(c)>opt(q->data[q->top]))
push(q,c);
else
{
while(opt(c)<=opt(q->data[q->top])&&!IsEmpty(q)&&q->data[q->top]!='(')
printf(" %c",pop(q));
push(q,c);
}
}
}
scanf("%c",&c);
}
while(!IsEmpty(q))
printf(" %c",pop(q));
printf("\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言 堆栈