程式實作中綴表達式轉換為字尾表達式,之間用空格分開。
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char Elemtype;
typedef struct
{
Elemtype *base;
Elemtype *top;
int stacksize;
}Stack;
void InitStack(Stack *s);
void Push(Stack *s, Elemtype e);
void Pop(Stack *s, Elemtype *e);
int StackLen(Stack s);
int main()
{
Stack s;
char c,d;
InitStack(&s);
printf("輸入:");
scanf("%c",&c);
while (c != '#')
{
while(c >= '0' && c <= '9')
{
printf("%c", c);
scanf("%c",&c);
if (c < '0' || c > '9')
{
printf(" ");
}
}
if (c == '(')
{
Push(&s, c);
}
else if (c == ')')
{
Pop(&s,&d);
while (d != '(')
{
printf("%c ",d);
Pop(&s,&d);
}
}
else if (c == '+' || c == '-')
{
if (!StackLen(s))
{
Push(&s, c);
}
else
{
Pop(&s, &d);
while (d != '('&& StackLen(s))
{
printf("%c ", d);
Pop(&s, &d);
}
if (d == '(')
{
Push(&s, d);
}
if (!StackLen(s))
{
printf("%c ",d);
}
Push(&s, c);
}
}
else if (c == '*' || c == '/')
{
if (!StackLen(s))
{
Push(&s, c);
}
else
{
Pop(&s, &d);
if (d == '+' || d == '-' || d=='(')
{
Push(&s, d);
}
else
{
printf("%c ", d);
}
Push(&s, c);
}
}
else if (c == '#')
{
break;
}
scanf("%c",&c);
}
while (StackLen(s))
{
Pop(&s, &d);
printf("%c ", d);
}
return 0;
}
void InitStack(Stack *s)
{
s->base = (Elemtype *)malloc(STACK_INIT_SIZE * sizeof(Elemtype));
if (!s->base)
{
exit(0);
}
s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}
void 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)
{
exit(0);
}
s->stacksize += STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop(Stack *s, Elemtype *e)
{
if (s->top == s->base)
{
exit(0);
}
s->top--;
*e = *(s->top);
}
int StackLen(Stack s)
{
return (s.top - s.base);
}
運算示例: