#include
#include
#define MAXSTACK 5
typedef struct
{
int sp;
int Data[MAXSTACK];
}STACK;
void Initialize(STACK *s);
int push(STACK *s,int item);
int pop(STACK *s,int *ret);
int full(STACK *s);
int empty(STACK *s);
void Initialize(STACK *s)
{
s->sp=0;
}
int push(STACK *s,int item)
{
if(full(s))
{
printf("Stack is full !!!\n");
return 0;
}
else
{
// printf("\tpush -> %d\n",item);
s->Data[s->sp++]=item;
}
return 1;
}
int full(STACK *s)
{
if(s->sp==MAXSTACK)
return 1;
return 0;
}
int pop(STACK *s,int *ret)
{
if(empty(s))
{
// printf("Stack is empty !!!\n");
return 0;
}
else
*ret=s->Data[--s->sp];
return 1;
}
int empty(STACK *s)
{
if(s->sp==0)
return 1;
return 0;
}
void main(void)
{
STACK s;
char *postfix="53+2*697-/+";
int left,right;
int input,result;
int i;
char *tmp;
tmp = (char *)malloc(2);
tmp[1] ='\0';
Initialize(&s);
for(i=0;postfix[i]!='\0';i++)
{
if(postfix[i]>='0' && postfix[i] <= '9')
{
tmp[0] = postfix[i];
input = atoi(tmp);
push(&s,input);
}
else{
if (pop(&s,&right))
if (pop(&s,&left))
{
switch (postfix[i]){
case '+':
result = left + right;
break;
case '-':
result = left - right;
break;
case '*':
result = left * right;
break;
case '/':
result = left / right;
break;
}
push(&s,result);
}
}
}
if (pop(&s,&right))
printf("%d",right);
printf("\n");
}
No comments:
Post a Comment