C语言实现中缀表达式转换为后缀表达式,给出代码实现
时间: 2023-03-13 09:35:42 浏览: 96
C语言实现中缀表达式转化后缀表达式
5星 · 资源好评率100%
C语言实现中缀表达式转换为后缀表达式可以使用以下代码: #include<stdio.h>
#include<string.h>
#define MAX 50
typedef struct{
char str[MAX];
int top;
}STACK; void push(STACK *s,char ele)
{
if(s->top==MAX-1)
{
printf("\n STACK OVERFLOW");
return;
}
s->top=s->top+1;
s->str[s->top]=ele;
} char pop(STACK *s)
{
if(s->top==-1)
{
printf("\n STACK UNDERFLOW");
return;
}
return(s->str[s->top--]);
} int pre(char ele)
{
switch(ele)
{
case '#':return 0;
case '(':return 1;
case '+':
case '-':return 2;
case '*':
case '/':return 3;
}
} char *infixtopostfix(char *infix,char *postfix)
{
STACK s;
int i=0,j=0;
char ele;
s.top=-1;
push(&s,'#');
while(infix[i]!='\0')
{
if(isalnum(infix[i]))
postfix[j++]=infix[i++];
else
{
if(pre(s.str[s.top])>pre(infix[i]))
{
ele=pop(&s);
postfix[j++]=ele;
}
else
push(&s,infix[i++]);
}
}
while(s.str[s.top]!='#')
{
ele=pop(&s);
postfix[j++]=ele;
}
postfix[j]='\0';
return postfix;
} int main()
{
STACK s;
char infix[MAX];
char postfix[MAX];
printf("\n Enter the Infix expression:");
scanf("%s",infix);
infixtopostfix(infix,postfix);
printf("\n The Postfix expression is: %s",postfix);
return 0;
}
阅读全文