Skip to content

Instantly share code, notes, and snippets.

@justjkk
Created April 24, 2010 17:32
Show Gist options
  • Save justjkk/377799 to your computer and use it in GitHub Desktop.
Save justjkk/377799 to your computer and use it in GitHub Desktop.
Evaluating postfix expression using Stack ADT
// Evaluating postfix expression using Stack ADT
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
typedef struct node
{
int data;
struct node *next;
}stack;
stack *topstk=NULL;
int push(int);
int pop(int *);
stack *getnode();
int evalpost(char *);
int calc(int,int,char);
void printerror();
void main()
{
char poststr[20];
printf("Enter Postfix string: ");
scanf("%s",poststr);
printf("The evaluated value of %s is %d\n",poststr,evalpost(poststr));
}
stack *getnode()
{
return ((stack *)malloc(sizeof(stack)));
}
int push(int val)
{
stack *top;
top = getnode();
if(top==NULL)
return -1;
top->data=val;
top->next=topstk;
topstk=top;
return 0;
}
int pop(int *val)
{
if(topstk==NULL)
return -1;
*val=topstk->data;
topstk=topstk->next;
return 0;
}
int calc(int a, int b, char c)
{
switch(c)
{
case '+': return a+b;
case '-': return a-b;
case '*': return a*b;
case '/': return a/b;
case '%': return a%b;
}
return 0;
}
int value(char ch)
{
int val;
printf("Enter the value of %c: ",ch);
scanf("%d",&val);
return val;
}
int evalpost(char *postexp)
{
int i=0,op1,op2;
char ch;
while((ch=postexp[i++])!='\0')
{
if(ch==' ')
continue;
if((tolower(ch)>='a')&&(tolower(ch)<='z'))
push(value(ch));
else if(ch=='+' || ch=='-' || ch=='*' || ch=='/' || ch=='%')
{
if(pop(&op2)||pop(&op1))
printerror();
push(calc(op1,op2,ch));
}
}
pop(&op1);
if(!pop(&op2))
printerror();
return op1;
}
void printerror()
{
printf("The given postfix is wrong\n");
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment