fork(3) download
  1. /*平成25年度春期応用情報技術者試験
  2. 午後問題問2 逆ポーランド表記法
  3. written by ◆g3C4s2T.1c
  4. */
  5.  
  6. #include <stdio.h>
  7.  
  8. /*---関数プロトタイプ宣言---*/
  9. char GetElement( int index );
  10. int GetPriority( char element );
  11.  
  12. /*---グローバル変数---*/
  13. char inputArray[] = {'1','+','2','*','3'};
  14.  
  15. int main(){
  16.  
  17. char result[100];
  18. int elementCount = 5;
  19.  
  20. int resultCount = 0;
  21. int stackCount = 0;
  22. char stack[100];
  23. stack[0] = NULL;
  24.  
  25. int i=1;
  26. while(i <= elementCount ){
  27.  
  28. int elementPriority = GetPriority(GetElement(i));
  29.  
  30. char stackTop = stack[stackCount];
  31. //演算要素をスタックからポップし、変換後配列の末尾に追加する。
  32. while( elementPriority <= GetPriority(stackTop) && stackTop != '(' ){
  33.  
  34. resultCount++;
  35. result[resultCount] = stackTop;
  36. stackCount--;
  37. stackTop = stack[stackCount];
  38.  
  39. }
  40. //変換前配列を参照し、演算要素を処理する。
  41. if( elementPriority == 1 ){
  42. stackCount--;
  43. }else{
  44. stackCount++;
  45. stack[stackCount] = GetElement(i);
  46. }
  47.  
  48. i++;
  49.  
  50. }
  51.  
  52. //スタックに残った演算要素を、変換後配列の末尾に追加する。
  53. while( stack[stackCount] != NULL ){
  54. resultCount++;
  55. result[resultCount] = stack[stackCount];
  56. stackCount--;
  57. }
  58.  
  59. for(i=1; i<=resultCount; ++i)
  60. printf("%c ", result[i]);
  61.  
  62. return 0;
  63. }
  64.  
  65. char GetElement( int index ){
  66.  
  67. return inputArray[index-1];
  68.  
  69. }
  70.  
  71. int GetPriority( char element ){
  72.  
  73. if(element == NULL)
  74. return 0;
  75.  
  76. switch( element ){
  77. case '(': return 5;
  78. case '*': return 3;
  79. case '/': return 3;
  80. case '+': return 2;
  81. case '-': return 2;
  82. case ')': return 1;
  83. //case NULL: return 0;
  84. default: return 4; //上記以外は数値と判断
  85. }
  86.  
  87. }
Success #stdin #stdout 0s 1832KB
stdin
Standard input is empty
stdout
1 2 3 * +