规则:从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,是符号则判断其与栈顶符号的优先级,是右括号或优先级低于栈顶符号,则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef char ElemType;
typedef struct
{
int maxsize;
ElemType *top;
ElemType *base;
}SqStack;
void init(SqStack* s, int n)
{
s->base = (ElemType*)malloc(sizeof(ElemType)*n);
if( !s->base )
{
exit(0);
}
s->maxsize = n;
s->top = s->base;
}
void push(SqStack* s, ElemType a)
{
if(s->top - s->base == s->maxsize)
{
printf("栈满!\n");
exit(0);
}
*s->top++ = a;
}
void pop(SqStack* s,ElemType *e)
{
if(s->top == s->base)
{
printf("栈已空\n");
return;
}
*e = *--s->top;
}
int StackLen(SqStack s)
{
return (s.top-s.base);
}
int main()
{
char c,e;
SqStack s;
printf("请输入中缀表达式,以#作为结束标志\n");
init(&s,20);
scanf("%c",&c);
while( c != '#')
{
while(c >= '0'&&c <= '9')
{
printf("%c",c);
scanf("%c",&c);
if(c < '0'|| c > '9')
{
printf(" ");
}
}
if(')' == c)
{
pop(&s,&e);
while('(' != e)
{
printf("%c",e);
pop(&s,&e);
}
}
else if('+' == c||'-' == c)
{
if(!StackLen(s)) //判空
{
push(&s,c);
}
else
{
do
{
pop(&s,&e);
if('(' == e)
{
push(&s,e);
}
else
{
printf("%c",e);
}
}while(StackLen(s)&&'(' != e);
push(&s,c);
}
}
else if('*' == c||'/' == c||'(' == c)
{
push(&s,c);
}
else if('#'==c)
{
break;
}
else
{
printf("输入错误\n");
return -1;
}
scanf("%c",&c);
}
while(StackLen(s))
{
pop(&s,&e);
printf("%c",e);
}
return 0;
}