Advertisement
ahmad_zizo

Untitled

Apr 15th, 2014
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. /* Stack has three properties. capacity stands for the maximum number of elements stack can hold.
  4. Size stands for the current size of the stack and elements is the array of elements */
  5. typedef struct Stack
  6. {
  7. int capacity;
  8. int size;
  9. int *elements;
  10. } Stack;
  11. /* crateStack function takes argument the maximum number of elements the stack can hold, creates
  12. a stack according to it and returns a pointer to the stack. */
  13. Stack * createStack(int maxElements)
  14. {
  15. /* Create a Stack */
  16. Stack *S;
  17. S = (Stack *)malloc(sizeof(Stack));
  18. /* Initialise its properties */
  19. S->elements = (int *)malloc(sizeof(int)*maxElements);
  20. S->size = 0;
  21. S->capacity = maxElements;
  22. /* Return the pointer */
  23. return S;
  24. }
  25. void pop(Stack *S)
  26. {
  27. S->size--;
  28. return;
  29. }
  30. int top(Stack *S)
  31. {
  32.  
  33.  
  34. return S->elements[S->size-1];
  35. }
  36. void push(Stack *S,int element)
  37. {
  38.  
  39. /* Push an element on the top of it and increase its size by one*/
  40. S->elements[S->size++] = element;
  41.  
  42. }
  43.  
  44. main()
  45. {
  46. Stack *S = createStack(40);
  47. char input[40];
  48. int i,n;
  49. printf("Enter Input\n");
  50. gets(input);
  51. for(i=0; input[i]!='\0'; i++)
  52. {
  53. if(input[i]<'10'&&input[i]>='0')
  54. push(S,input[i]);
  55. if(input[i]=='+')
  56. {
  57. n=top(S)-'0';
  58. pop(S);
  59. n=n+top(S)-'0';
  60. pop(S);
  61. push(S,n);
  62. }
  63. if(input[i]=='-')
  64. {
  65. n=top(S);
  66. pop(S);
  67. n=n-top(S);
  68. pop(S);
  69. push(S,n);
  70. }
  71. if(input[i]=='*')
  72. {
  73. n=top(S)-'0';
  74. pop(S);
  75. n=n*(top(S)-'0');
  76. pop(S);
  77. push(S,n);
  78. }
  79. if(input[i]=='/')
  80. {
  81. n=top(S)-'0';
  82. pop(S);
  83. n=n/(top(S)-'0');
  84. pop(S);
  85. push(S,n);
  86. }
  87. }
  88. printf("answer = %d",top(S));
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement