Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.20 KB | None | 0 0
  1. #include<stdio.h>    
  2. #include<string.h>      
  3. #define MAX 50          
  4. int stack[MAX];          
  5. char post[MAX];          
  6. int top=-1;              
  7. void pushstack(char a);  
  8. void pushstack2(char a);  
  9. void evaluate(char c);  
  10. int main()
  11. {
  12.     int i,l;
  13.     printf("NOTE: Remember to inlcude SPACE (' ') between each element, but negative must be written normaly.\n");
  14.     printf("Insert a postfix notation :: ");
  15.     gets(post);                  
  16.     l=strlen(post);              
  17.     for(i=0;i<l;i++)
  18.     {
  19.         if(post[i] == ' '){
  20.             continue;
  21.         }
  22.         else if(post[i] == '-' && post[i+1]>='0' && post[i+1]<='9'){
  23.             pushstack2 (post [i+1]);
  24.             i++;
  25.         }
  26.         else if(post[i]>='0' && post[i]<='9')
  27.         {
  28.             pushstack(post[i]);        
  29.         }
  30.         else if(post[i]=='+' || post[i]=='-' || post[i]=='*' || post[i]=='/' || post[i]=='^')      
  31.         {
  32.             evaluate(post[i]);          
  33.         }
  34.  
  35.     }                      
  36.     printf("\n\nResult = %d",stack[top]);
  37.  
  38.     return 0;
  39. }
  40.  
  41. void pushstack2(char a)        
  42. {
  43.     top++;                              
  44.     stack[top]=(int) a - 48;  
  45.     stack[top]=-stack[top];
  46. }
  47.  
  48. void pushstack(char a)        
  49. {
  50.     top++;                            
  51.     stack[top]=(int) a - 48;  
  52. }
  53.  
  54. void evaluate(char c)      
  55. {
  56.     int a,b,ans;      
  57.     a=stack[top];      
  58.     stack[top]='\0';
  59.     pop();    
  60.     top--;                
  61.     b=stack[top];        
  62.     stack[top]='\0';      
  63.     top--;                
  64.     switch(c)    
  65.     {
  66.         case '+':          
  67.             ans=b+a;
  68.             break;
  69.         case '-':          
  70.             ans=b-a;
  71.             break;
  72.         case '*':            
  73.             ans=b*a;
  74.             break;
  75.         case '/':          
  76.             ans=b/a;
  77.             break;
  78.     }
  79.     top++;            
  80.     stack[top]=ans;        
  81. }
  82. void push (int elem) {
  83.     if (top >= MAX){
  84.         puts("Stack Full!\n");
  85.     }
  86.     else{
  87.         stack [top++] = elem;
  88.     }
  89. }
  90. void pop(){
  91.     top--;
  92.     if(top < 0){
  93.         printf("Stack empty.");
  94.         return -1;
  95.     }
  96.     else{
  97.         return (stack[top]);
  98.     }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement