fork download
  1. #include<stdio.h>
  2. char buf[256];
  3. int idx;
  4. int stack[100];
  5. int sp;
  6. #define push(type,x) (stack[sp++]=(type<<8)|x)
  7. #define pop() (stack[--sp]&0xff)
  8. #define toptype() (stack[sp-1]>>8)
  9.  
  10. int gettoken(char a[]){
  11. while(buf[idx]==' ')idx++;
  12. if(buf[idx]=='\0') return 0;
  13. int i;
  14. for(i=0;;){
  15. switch(buf[idx]){
  16. case'\0':
  17. case' ':
  18. a[i]='\0';
  19. return 4;
  20. case'+': case'-':
  21. if(i==0){
  22. a[i++]=buf[idx++];
  23. a[i]='\0';
  24. return 2;
  25. }
  26. a[i]='\0';
  27. return 4;
  28. case'*': case'/': case'%':
  29. if(i==0){
  30. a[i++]=buf[idx++];
  31. a[i]='\0';
  32. return 1;
  33. }
  34. a[i]='\0';
  35. return 4;
  36. case'(': case')':
  37. if(i==0){
  38. a[i++]=buf[idx++];
  39. a[i]='\0';
  40. return 3;
  41. }
  42. a[i]='\0';
  43. return 4;
  44. default:
  45. a[i++]=buf[idx++];
  46. }
  47. }
  48. }
  49.  
  50. void popto(int type){
  51. int i;
  52. while(toptype()!=type){
  53. printf("%c ",pop());
  54. }
  55. pop();
  56. }
  57. int main(){
  58. int a,b;
  59. scanf("%d",&a);
  60. for(b=0;b<=a;b++){
  61. gets(buf);
  62. idx=0;
  63. int i,type;
  64. char a[64];
  65. sp=0;
  66. push(3,'(');
  67. for(i=1;(type=gettoken(a));i++){
  68. switch(type){
  69. case 1:
  70. case 2:
  71. while(toptype()<=type)
  72. printf("%c ",pop());
  73. push(type, a[0]);
  74. break;
  75. case 3:
  76. if(a[0]=='(')
  77. push(type,a[0]);
  78. else popto(type);
  79. break;
  80. case 4:
  81.  
  82. printf("%s",a);
  83. if(a[0]!='\0'){printf(" ");}
  84. break;
  85.  
  86.  
  87. }
  88. }
  89. popto(3);
  90. if(b>=1)printf("\n");}
  91.  
  92. return 0;
  93.  
  94. }
Runtime error #stdin #stdout 0.02s 2056KB
stdin
Standard input is empty
stdout