fork(1) download
  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. class stk{
  5. private: char c[20];
  6. private: int id=-1;
  7. public: int isempty(){
  8. if(id==-1)
  9. return 1;
  10. else
  11. return 0;
  12. }
  13. public: void push(char o){
  14. c[++id]=o;
  15. }
  16. public: char pop(){
  17. return c[id--];
  18. }
  19. };
  20.  
  21. int main(){
  22. stk stack;
  23. char n[21];
  24. char preo;
  25. int i=0;
  26. cin>>n;
  27. int f=1;
  28. while(i<strlen(n)){
  29. if(n[i]>='0'&&n[i]<='9'){
  30. if(f)
  31. f=0;
  32. else
  33. cout<<" ";
  34. while(i<strlen(n)&&n[i]>='0'&&n[i]<='9'){
  35. cout<<n[i];
  36. i++;
  37. }
  38. }
  39. if(i<strlen(n)){
  40. if(stack.isempty())
  41. stack.push(n[i++]);
  42. else{
  43. preo=stack.pop();
  44. if(n[i]=='+'||n[i]=='-'){
  45. if(preo!='(')
  46. cout<<" "<<preo;
  47. else
  48. stack.push(preo);
  49. stack.push(n[i]);
  50. }else if(n[i]=='*'||n[i]=='/'){
  51. if(preo=='*'||preo=='/')
  52. cout<<" "<<preo;
  53. else
  54. stack.push(preo);
  55. stack.push(n[i]);
  56.  
  57. }else if(n[i]=='('){
  58. stack.push(preo);
  59. stack.push(n[i]);
  60. }else{
  61. while(preo!='('){
  62. cout<<" "<<preo;
  63. preo=stack.pop();
  64. }
  65. }
  66. i++;
  67. }
  68. }
  69. }
  70. while(!stack.isempty())
  71. cout<<" "<<stack.pop();
  72. }
Success #stdin #stdout 0s 3472KB
stdin
2+3*(7-4)
stdout
2 3 7 4 - * +