Infix to Postfix Coding Problem
Code:
#include<stdio.h>
#include<string.h>
#define STACKSIZE 100
typedef int Item_t;
typedef struct {
Item_t Items[STACKSIZE];
int Top;
} stack_t;
void Initializes_Stack(stack_t *);
int EmptyStack(stack_t);
int FullStack(stack_t);
void Push(Item_t X, stack_t *);
void Pop(stack_t *s, Item_t *);
int is_operand(Item_t);
int is_operator(Item_t);
int HigherPrecedence(Item_t, Item_t);
void Postfix(stack_t *);
void Initializes_Stack(stack_t *s){
s->Top =0;
}
int EmptyStack(stack_t s){
return (s.Top == 0);
}
int FullStack(stack_t s){
return (s.Top==STACKSIZE);
}
void Push(Item_t x, stack_t *s){
if(FullStack(*s))
printf("\nERROR: Stack overflow!\n");
else {
s->Items[s->Top]=x;
++(s->Top);
}
}
void Pop(stack_t *s, Item_t *x)
{
if(EmptyStack(*s))
printf("\nERROR: Empty stack.\n");
else {
--(s->Top);
*x=s->Items[s->Top];
}
}
int is_operand(Item_t data)
{
if (((data >= 'a') && (data <= 'z')) ||
((data >= 'A') && (data <= 'Z')) ||
((data >= '0') && (data <= '9')))
return 1;
else
return 0;
}
int HigherPrecedence(Item_t OperatorA, Item_t OperatorB)
{
if (OperatorA == '(')
return 0;
else if (OperatorB == '(')
return 0;
else if (OperatorB == ')')
return 1;
else if ((OperatorA == '^') && (OperatorB == '^'))
return 0;
else if (OperatorA == '^')
return 1;
else if (OperatorB == '^')
return 0;
else if ((OperatorA == '*') || (OperatorA == '/'))
return 1;
else if ((OperatorB == '*') || (OperatorB == '/'))
return 0;
else
return 1;
}
void Postfix(stack_t *s)
{
Item_t ch,pop;
ch=getchar();
if( ch != '\n' )
{
if(is_operand(ch))
putchar(ch);
else
{
while(!EmptyStack(*s) && HigherPrecedence(s->Items[s->Top], ch)){
Pop(s,&pop);
if(pop!='(')
putchar(pop);
}
if ( (!EmptyStack(*s)) && (ch == ')') )
Pop(s,&pop);
else
Push(ch,s);
}
Postfix(s);
}
else
{
while(!EmptyStack(*s)){
Pop(s,&pop);
if(pop!=')')
putchar(pop);
}
}
}
int main(void)
{
stack_t s;
Item_t in='y';
Initializes_Stack(&s);
printf("Enter an infix expression:");
Postfix(&s);
putchar('\n');
return 0;
}
:confused: This program will missed up some expression when there are parentheses... and dunno why it didn't skip '(' or ')' without adding if(pop!=')') and if(pop!='(')...