Skip to content

Commit 590003f

Browse files
Merge pull request #1 from SumeetHaryani/logical-problems
postfix-expression evaluation problem
2 parents 80d5d72 + 28dee28 commit 590003f

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 numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

0 commit comments

Comments
 (0)