File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11+ stack
22+ next greater element
3- + postfix evaluation
4- + balanced parentheses
3+ + balanced parentheses
Original file line number Diff line number Diff line change 1+ function postFixEvaluation ( expression ) {
2+ if ( typeof expression !== 'string' || expression . length === 0 ) {
3+ throw 'Invalid post fix expression.' ;
4+ }
5+
6+ var stack = [ ] ;
7+ for ( var i = 0 ; i < expression . length ; i ++ ) {
8+ var curr = expression [ i ] ;
9+ if ( curr . match ( / ^ \d $ / ) ) {
10+ stack . push ( curr - '0' ) ;
11+ } else if ( curr . match ( / ^ [ + - / * ] $ / ) ) {
12+ if ( stack . length < 2 ) {
13+ throw 'Invalid post fix expression.' ;
14+ }
15+
16+ var op = {
17+ '+' : function ( a , b ) { return a + b } ,
18+ '-' : function ( a , b ) { return b - a } ,
19+ '/' : function ( a , b ) { return b / a } ,
20+ '*' : function ( a , b ) { return a * b }
21+ } ;
22+ var first = stack . pop ( ) ;
23+ var second = stack . pop ( ) ;
24+
25+ stack . push ( op [ curr ] ( first , second ) ) ;
26+ } else {
27+ throw 'Invalid post fix expression.' ;
28+ }
29+ }
30+
31+ return stack . pop ( ) ;
32+ }
33+
34+ console . log ( postFixEvaluation ( "235*+8-" ) ) ; // === 9
35+ console . log ( postFixEvaluation ( "23/" ) ) ; // === 0.66
You can’t perform that action at this time.
0 commit comments