#include "stdafx.h"
#include "malloc.h"
#include "windows.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define INIT_SIZE 20
#define INCRESEMENT 10
#define MAXBUFFER 10
typedef char ElemType;
typedef struct
{
int stacksize;
ElemType *base;
ElemType *top;
}sqStack;
void initStack(sqStack *s)
{
s->base = (ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
if(!s->base) exit(0);
s->top = s->base;
s->stacksize = INIT_SIZE;
}
void Push(sqStack *s, ElemType e)
{
if(s->top - s->base >= s->stacksize)
{
s->base = (ElemType*)realloc(s->base, (s->stacksize+INCRESEMENT)*sizeof(ElemType));
if(!s->base) exit(0);
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack*s, ElemType *e)
{
if(s->base == s->top) return;
s->top--;
*e = *(s->top);
}
int StackLen(sqStack s)
{
return (s.top-s.base);
}
int Priority(sqStack s)
{
if(s.base == s.top) return 0;
else
{
s.top--;
switch(*s.top)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '(':
return -1;
}
}
}
int decidec( ElemType e)
{
if(isdigit(e) || e=='.') return 0;
if(e=='*' || e=='/' || e=='(') return 1;
if(e==')') return 2;
else return 3;
}
int main(int argc, char* argv[])
{
sqStack s;
initStack(&s);
printf("输入中缀式(#结束):\n");
char c;
scanf("%c",&c);
char str[MAXBUFFER];
ElemType x;
int i = 0;
while(c!='#')
{
switch(decidec(c))
{
case 0:
while(!decidec(c))
{
printf("%c",c);
scanf("%c",&c);
}
printf(" ");
break;
case 1:
Push(&s, c);
scanf("%c",&c);
break;
case 2:
while(StackLen(s)){
Pop(&s, &x);
if(x=='(') break;
else printf("%c ",x);
}
scanf("%c",&c);
break;
case 3:
if(Priority(s)==2)
{
while(StackLen(s)){
Pop(&s, &x);
if(x=='(') break;
else printf("%c ",x);
}
}
else Push(&s,c);
scanf("%c",&c);
break;
}
}
while(StackLen(s))
{
Pop(&s, &x);
printf("%c ",x);
}
printf("\n");
return 0;
}
栈-中缀式转后缀式
最新推荐文章于 2021-04-13 22:10:06 发布
