Advertisement
Guest User

Untitled

a guest
Apr 8th, 2020
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 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]=='/')      
  31.         {
  32.             evaluate(post[i]);          
  33.         }
  34.  
  35.     }                      
  36.     printf("\n\nResult = %d\n",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.     pop();              
  65.     switch(c)    
  66.     {
  67.         case '+':          
  68.             ans=b+a;
  69.             break;
  70.         case '-':          
  71.             ans=b-a;
  72.             break;
  73.         case '*':            
  74.             ans=b*a;
  75.             break;
  76.         case '/':          
  77.             ans=b/a;
  78.             break;
  79.     }
  80.     top++;            
  81.     stack[top]=ans;        
  82. }
  83. /*void push (char elem) {
  84.     if (top >= MAX){
  85.         puts("Stack Full!\n");
  86.     }
  87.     else{
  88.         stack [top++] = elem;
  89.     }
  90. }*/
  91. int pop(){
  92.     top--;
  93.     if(top < 0){
  94.         printf("Stack empty.");
  95.         return -1;
  96.     }
  97.     else{
  98.         return (stack[top]);
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement