//DSPP-Infix-to-Postfix:中序轉後序(整數運算)
//輸入:
//中序整數運算表示法。
//
//輸出:
//後序整數運算表示法。
//所有運算元及運算子都以一個Space隔開
//修改以下程式
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define SIZE 100
typedef struct
{
size_t top;
int items[SIZE];
} STACK;
int isFull_stack(STACK *);
int isEmpty_stack(STACK *);
void push_stack(STACK *, int );
int pop_stack(STACK *);
void postfix(char [], STACK *);
int priority(char );
int main( void )
{
STACK s={0};
char c;
char in[80];
int i=0;
while ( scanf("%c",&c) ){ //A+B-C*D-(E+F/G)
if(c!= ' ') in[i++] = c;
if ( c == 10 ) break;
}
postfix(in,&s);
}
int isFull_stack(STACK *s)
{
return (s->top == SIZE)?1:0;
}
int isEmpty_stack(STACK *s)
{
return (s->top == 0)?1:0;
}
void push_stack(STACK *s, int a)
{
if ( isFull_stack(s) )
{
fprintf(stderr,"%s","stack is overflow\n");
exit(1);
}
else
{
s->items[s->top++] = a;
//fprintf(stdout,"%d is pushed into stack. top=%d\n",a,s->top);
}
}
int pop_stack(STACK *s)
{
int tmp;
if ( isEmpty_stack(s) )
{
fprintf(stderr,"%s","stack is underflow\n");
exit(2);
}
else
{
tmp = s->items[--s->top];
//fprintf(stdout,"%d is popped from stack. top=%d\n",tmp,s->top);
return tmp;
}
}
void postfix(char infix[], STACK *s)
{
int i=0;
char c,tmp;
while ( (c=infix[i++]) != 10 ) // newline
{
if ( isalpha(c) ) printf("%c ",c);//operands
if ( isdigit(c) ){
int d = c - 48;
while(isdigit(c = infix[i++]))
d = d*10 + (c-48);
printf("%d ",d);
}
if ( c == '(' )
push_stack(s,c);
else if ( c == ')' )
{
while ( (tmp = pop_stack(s)) != '(' )
printf("%c ",tmp);
}
else
{
while ( !isEmpty_stack(s) && priority(c) <= priority(s->items[s->top-1]) )
// <= for left associative, < for right associative
{
tmp = pop_stack(s);
if (tmp != '(') printf("%c ",tmp);
}
push_stack(s,c);
}
}
while ( !isEmpty_stack(s))
printf("%c ",pop_stack(s));
}
int priority(char c)
{
switch(c)
{
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '(':
default:
return 0;
}
}
Translate
2014年11月15日 星期六
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言