private static List < Tokenizer . Token > toReversePolishNotation ( List < Tokenizer . Token > tokens ) { LinkedList < Tokenizer . Token > queue = new LinkedList < Tokenizer . Token > ( ) ; Stack < Tokenizer . Token > stack = new Stack < Tokenizer . Token > ( ) ; for ( int i = 0 ; i < tokens . size ( ) ; i ++ ) { Tokenizer . Token token = tokens . get ( i ) ; switch ( token . type ) { case VERSION : queue . add ( token ) ; break ; case CLOSING : while ( stack . peek ( ) . type != Tokenizer . TokenType . OPENING ) { queue . add ( stack . pop ( ) ) ; } stack . pop ( ) ; if ( stack . size ( ) > 0 && stack . peek ( ) . type . isUnary ( ) ) { queue . add ( stack . pop ( ) ) ; } break ; default : if ( token . type . isUnary ( ) ) { queue . push ( token ) ; i ++ ; queue . push ( tokens . get ( i ) ) ; } else { stack . push ( token ) ; } break ; } } while ( ! stack . isEmpty ( ) ) { queue . add ( stack . pop ( ) ) ; } Collections . reverse ( queue ) ; return queue ; }
Adaptation of the shutting yard algorithm