• Source
    1.  
    2. /*
    3. ****************************************
    4. Problem: Postfix to Infix conversion
    5. ****************************************
    6. Ashis Kumar Chanda
    7. ID: 1624
    8. CSE, DU
    9. ****************************************
    10. ****************************************
    11. */
    12. // Uva Problem: 727
    13.  
    14. // *, / sign have same precidence
    15. // but greater precidence than +,-
    16. #include<stdio.h>
    17. #include<string.h>
    18. #include<stdlib.h>
    19. #include <iostream>
    20.  
    21. using namespace std;
    22.  
    23. #define Max 100
    24. int pushnum,j; // j is index of p_str
    25. char p_str[Max];
    26.  
    27. int checkOperator(char p)
    28. {
    29. if(p=='+' || p=='-')
    30. return 1;
    31. else if( p==42 || p==47)
    32. return 2;
    33.  
    34. return 0;
    35. }
    36.  
    37. void pus( int push, int array[])
    38. {
    39. int i,current, pre;
    40.  
    41. while(1){
    42. current=checkOperator(push);
    43. pre=checkOperator(array[pushnum-1] );
    44.  
    45. // checking operator precidence
    46. if( (current ==1 && pre ==1) || (current ==1 && pre==2) ||(current==2 && pre ==2) )
    47. {
    48. p_str[j]=array[pushnum-1];
    49. j++;
    50. pushnum=pushnum-1;
    51. }
    52. else
    53. break;
    54. }
    55.  
    56. for(i=0;i<Max;i++)
    57. if(i==pushnum)
    58. {
    59. array[i]=push;
    60. break;
    61. }
    62. pushnum++;
    63. }
    64.  
    65. void pop(int array[])
    66. {
    67. int i;
    68. pushnum--;
    69.  
    70. for(i=0;pushnum>=0;i++){
    71. if(array[pushnum]==40)// checking '('
    72. break;
    73. else
    74. {
    75. p_str[j]=array[pushnum];
    76. j++;
    77. pushnum--;
    78. }
    79. }
    80.  
    81. }
    82.  
    83. int main()
    84. {
    85. char str[Max];
    86.  
    87. gets(str);
    88. pushnum=0; // gloval variable
    89. j=0;
    90. int i,array[Max]={0};
    91.  
    92. for(i=0,j=0 ;str[i]!=NULL;i++){
    93.  
    94. if(str[i]>='0' && str[i]<= '9')
    95. {
    96. p_str[j]=str[i];
    97. j++;
    98. }
    99. else if(str[i]==' ')
    100. continue;
    101. else if(str[i]=='+')
    102. pus(43,array);
    103. else if(str[i]=='-')
    104. pus(45,array);
    105. else if (str[i]==47)
    106. pus(47,array);
    107. else if(str[i]== '*')
    108. pus(42,array);
    109. else if(str[i]== '(')
    110. pus(40,array);
    111. else if(str[i]== ')')
    112. pop(array);
    113. }
    114.  
    115. pop(array);
    116. p_str[j]=NULL;
    117.  
    118. printf("\nPostfix is : ");
    119. printf("%s\n",p_str);
    120.  
    121. return 0;
    122. }
    123.  
    124. /*
    125.  
    126. input :
    127.  
    128. 5*(6+2)-3
    129. (2+3) *5+(3*4)
    130. 5*6+ ((4/2*3+6) (6+7*2) +3)+9
    131.  
    132. Output:
    133. 562+*3-
    134. 23+5*34*+
    135. 56*42/3 *6+672*++3++9+
    136.  
    137. */
    138.