Advertisement
ahmad_zizo

Untitled

Apr 28th, 2014
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct
  5. {
  6. int top;
  7. int items[100];
  8. } Stack;
  9. void initialize(Stack *s)
  10. {
  11. s->top=0;
  12. }
  13. void push(Stack *s,int value)
  14. {
  15. s->items[s->top++]=value;
  16. }
  17. int pop(Stack *s)
  18. {
  19. return s->items[--s->top];
  20. }
  21. int isfull(Stack *s)
  22. {
  23. return s->top<100?0:1 ;
  24. }
  25. int isempty(Stack *s)
  26. {
  27. return s->top==0?1:0;
  28. }
  29.  
  30. int postfix(char str[])
  31. {
  32. Stack s;
  33. initialize(&s);
  34. int i;
  35. for (i=0; i<strlen(str); i++)
  36. {
  37. if (str[i]==' ')
  38. continue;
  39. if (str[i]<='9' && str[i]>='0')
  40. push(&s,str[i]-'0');
  41. else
  42. {
  43. int a,b;
  44. if (isempty(&s))
  45. printf("error.\n\n");
  46. else
  47. a=pop(&s);
  48. if (isempty(&s))
  49. printf("error.\n");
  50. else b=pop(&s);
  51. switch(str[i])
  52. {
  53. case '+':
  54. push(&s,b+a);
  55. break;
  56. case '-':
  57. push(&s,b-a);
  58. break;
  59. case '*':
  60. push(&s,b*a);
  61. break;
  62. case '/':
  63. push(&s,b/a);
  64. break;
  65. default:
  66. printf("error.\n");
  67. }
  68. }
  69. }
  70. return pop(&s);
  71. }
  72. int main()
  73. {
  74. char str[20];
  75. gets(str);
  76. printf("\n\n%s=%d",str,postfix(str));
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement