Advertisement
tsnaik

Postfix expression evaluation

Oct 22nd, 2014
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<ctype.h>
  4. struct node
  5. {
  6.     int data;
  7.     struct node *next;
  8. };
  9.  
  10. void push(int, struct node **);
  11. int pop(struct node **);
  12. int eval(int, int, char);
  13.  
  14.  
  15. void main()
  16. {
  17.     char c;
  18.     struct node *start=NULL;
  19.  
  20.     while((c=getchar())!='\n')
  21.     {
  22.         if(isdigit(c))
  23.         {
  24.             push((c-'0'),&start);
  25.         }
  26.  
  27.         if(c=='*' || c=='/' || c=='+' || c=='-')
  28.         {
  29.  
  30.             push(eval(pop(&start),pop(&start), c),&start);
  31.         }
  32.     }
  33.  
  34.     printf("\nAnswer is: %d", pop(&start));
  35.  
  36. }
  37. void push(int element, struct node **start)
  38. {
  39.  
  40.         struct node *new;
  41.         new=(struct node *) (malloc(sizeof(struct node)));
  42.  
  43.     new->data=element;
  44.  
  45.         new->next=NULL;
  46.         if((*start)==NULL)
  47.         {
  48.                 *start=new;
  49.  
  50.                 return;
  51.         }
  52.         new->next=*start;
  53.  
  54.         *start=new;
  55. }
  56.  
  57. int pop(struct node **start)
  58.  {
  59.     struct node *p;
  60.     int x;
  61.  
  62.         p=(*start);
  63.         (*start)=(p->next);
  64.     x=p->data;
  65.         free(p);
  66.         return(x);
  67.  
  68.  }
  69.  
  70. int eval(int top, int bot, char c)
  71.  
  72. {
  73.         printf("\n %d %d %c",top,bot,c);
  74.     switch(c)
  75.     {
  76.     //  printf("\n %d %d %c",top,bot,c);
  77.         case '+':
  78.             return (bot+top);
  79.         case '/':
  80.             return (bot/top);
  81.         case '*':
  82.             return (bot*top);
  83.         case '-':
  84.             return (bot-top);
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement