中缀表达式 转后缀表达式

2018-01-25 10:57:47来源:网络收集作者:纳米程序员人点击

分享
第七城市

[var1]#include
#include
#include
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 5
typedef char ElemType;
typedef int STATUS;
typedef struct Stack {
ElemType * top;
ElemType *base;
int stackSize;
}stack;
STATUS initStack(stack * s)
{
s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
return OK;
}
STATUS Push(stack *s, ElemType e)
{
if (s->top - s->base >= s->stackSize)
{
s->base = (ElemType*)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if (!s->base)return ERROR;
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACKINCREMENT;
}
*(s->top) = e;
++s->top;
return OK;
}
STATUS Pop(stack *s, ElemType * e)
{
if (s->base == s->top)return ERROR;
--s->top;
*e = *(s->top);
return OK;
}
STATUS clearStack(stack *s)
{
s->top = s->base;
return OK;
}
STATUS destoryStack(stack *s)
{
//for (int i = 0; i < s->stackSize; i++)
//{
free(s->base);
//s->base++;
//}
//printf("%d", *(s->base));
s->base = 0;
s->top = 0;
s->stackSize = 0;
return OK;
}
int StackLen(stack *s)
{return (s->top - s->base);//一定要加括号
}
int main(int argc, char * argv[])
{
stack s;
int count = 0;
char c,k;
initStack(&s);//初始化栈
printf("请输入要转换的中缀表达式:'#'结束/n");
scanf("%c", &c);
while (c != '#')
{
while (isdigit(c) || c == '.')
{
printf("%c", c);
scanf("%c", &c);
if (!isdigit(c))printf(" ");
}
if ('#' == c)//判断第二个while循环里面的输入除了数字的情况
{
break;
}
else if('('==c || '*'==c || '/'==c)//优先级最高,直接push
{
Push(&s, c);
}
else if ('+' == c || '-' == c)
{
if (StackLen(&s) == 0)
{
Push(&s, c);
}
else
{
Pop(&s, &k);
if ('*' == k || '/' == k)
{
printf("%c ", k);while (StackLen(&s) != 0&&'(' != k)
{
Pop(&s, &k);
if ('(' != k)printf("%c ", k);}
if ('(' == k) Push(&s, k);
Push(&s, c);
}
else
{
Push(&s, k);
Push(&s, c);
}}
}
else if (')' == c)
{
do
{
Pop(&s, &k);
if ('(' != k)printf("%c ", k);
} while ('('!=k);
}
//else {
//printf("输入错误!");
//break;
//}
scanf("%c", &c);
}
count = StackLen(&s);
for (int i = 0; i < count; i++)
{
Pop(&s, &k);
printf("%c ", k);
}
//-------------------
//destoryStack(&s);
system("pause");
return 0;
}
第七城市

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台