Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. typedef struct {
  5.  
  6. int top;
  7. char container[20];
  8.  
  9.  
  10. }stack ;
  11. int isempty(stack *s)
  12. {
  13. if(s->top==-1)
  14. {
  15. return 1;
  16. }
  17. else
  18. return 0;
  19. }
  20. void push(stack *s,char x)
  21. {
  22. s->container[++s->top]=x;
  23. printf(" \n pushed %c at %d \n",x,s->top);
  24.  
  25. }
  26. char pop (stack *s)
  27. {
  28. if(isempty(s))
  29. {
  30. return 0;
  31. }
  32. else
  33. {
  34. return (s->container[s->top--]);
  35.  
  36. }
  37. }
  38. int getorder(char op)
  39. {
  40. if(op=='(')
  41. return 0;
  42. if(op=='-')
  43. return 1;
  44. if(op=='+')
  45. return 2 ;
  46. if(op=='*')
  47. return 4;
  48. if(op=='/')
  49. return 3;
  50.  
  51. }
  52. int main (){
  53.  
  54. char eqn[]="( 10 + 2.5 ) * 4 + 3";
  55. char *token;
  56. char token2[1];
  57. char neweqn[50]=" ";
  58. stack *s=malloc(sizeof(stack));
  59. s->top=-1;
  60. char *ch1;
  61.  
  62. token=strtok (eqn," ");
  63. while(token!=NULL)
  64. {
  65. printf("token now is %c \n",token[0]);
  66.  
  67. if(token[0]=='+'||token[0]=='-'||token[0]=='/'||token[0]=='*'||token[0]=='(')
  68. {
  69.  
  70. printf("operator %c\n",token[0]);
  71.  
  72. if(s->top==-1 ||token[0]=='('|| getorder(token[0])>getorder(s->container[s->top]))
  73. {
  74.  
  75. push(s,token[0]);
  76. }
  77.  
  78. else{
  79.  
  80. while(!isempty(s))
  81. {
  82.  
  83. ch1=pop(s);
  84. if (ch1=='('){break;}
  85. token2[0]=ch1;
  86. strcat(neweqn,token2);
  87. }
  88. push(s,token[0]);
  89. }
  90.  
  91. }
  92. else if(!strcmp(token,")"))
  93. {
  94.  
  95.  
  96. ch1=pop(s);
  97. printf("popped %c \n",ch1);
  98. while(ch1!='(')
  99. {
  100. token2[0]=ch1;
  101. strcat(neweqn,token2);
  102. ch1=pop(s);
  103.  
  104. }
  105. }
  106. else
  107. {
  108.  
  109. strcat(neweqn,token);
  110.  
  111. }
  112.  
  113.  
  114.  
  115.  
  116. token=strtok(NULL," ");
  117.  
  118. }
  119. ch1=pop(s);
  120. token2[0]=ch1;
  121. strcat(neweqn,token2);
  122. printf("new eqn .. %s \n",neweqn);
  123.  
  124.  
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.  
  137.  
  138.  
  139. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement