#UVa:727-Equation

灆洢 2012-01-17 23:33:11

利用Stack將中序運算式換成後序運算式。

C++(0.056)

/*******************************************************/
/* UVa 727 Equation                                    */
/* Author: Maplewing [at] knightzone.studio            */
/* Version: 2012/01/17                                 */
/*******************************************************/
#include<iostream>
#include<cstdio>
#include<cctype>
#include<stack>
using namespace std;

int main(){
  int n;
  char c;
  stack<char> stk;
  while( scanf( "%d", &n ) != EOF ){
    getchar();
    getchar();
    for( int i = 0 ; i < n ; i++ ){
      if( i ) printf( "\n" );
      while( scanf( "%c", &c ) != EOF && c != '\n'){
        getchar();
        if( isdigit(c) )
          printf( "%c", c );
        else if( c == '(' )
          stk.push(c);
        else if( c == '*' || c == '/' ){
          while( !stk.empty() && (stk.top() == '*' || stk.top() == '/') ){
            printf( "%c", stk.top() );
            stk.pop();
          }
          stk.push(c);
        }
        else if( c == '+' || c == '-' ){
          while( !stk.empty() &&
                 (stk.top() == '*' ||
                  stk.top() == '/' ||
                  stk.top() == '+' ||
                  stk.top() == '-' )){
            printf( "%c", stk.top() );
            stk.pop();
          }
          stk.push(c);
        }
        else if( c == ')' ){
          while( stk.top() != '(' ){
            printf( "%c", stk.top() );
            stk.pop();
          }
          stk.pop();
        }
      }
      while( !stk.empty() ){
        printf( "%c", stk.top() );
        stk.pop();
      }
      printf( "\n" );
    }
  }
  return 0;
}

發表迴響

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料