File tree 1 file changed +44
-0
lines changed
src/_DataStructures_/Stack/postfix-expression-evaluation
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Evaluation of Postfix Expression
3
+ * Input:456*+
4
+ * Output:34
5
+ */
6
+
7
+ const Stack = require ( '../index' ) ;
8
+
9
+ function evaluatePostfixExpression ( expression ) {
10
+ let s = new Stack ( ) ;
11
+ for ( let i = 0 ; i < expression . length ; i ++ ) {
12
+ const char = expression [ i ] ;
13
+ if ( ! isNaN ( char ) ) {
14
+ //if number push the char onto stack
15
+ s . push ( Number ( char ) ) ;
16
+ } else {
17
+ // if char is an operator then pop two elements from stack, evaluate them accordingly based on operator.
18
+ //push the result to stack
19
+ let val1 = s . pop ( ) ;
20
+ let val2 = s . pop ( )
21
+ switch ( char ) {
22
+ case '+' :
23
+ s . push ( val2 + val1 ) ;
24
+ break ;
25
+ case '-' :
26
+ s . push ( val2 - val1 ) ;
27
+ break ;
28
+ case '*' :
29
+ s . push ( val2 * val1 ) ;
30
+ break ;
31
+ case '/' :
32
+ s . push ( val2 / val1 ) ;
33
+ break ;
34
+
35
+ }
36
+ }
37
+ }
38
+ //pop the value of postfix expression
39
+ return s . pop ( ) ;
40
+ }
41
+
42
+ console . log ( evaluatePostfixExpression ( "123+*8-" ) ) ; // -3
43
+
44
+ console . log ( evaluatePostfixExpression ( "12345*+*+" ) ) ; // 47
You can’t perform that action at this time.
0 commit comments