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