Skip to content

Commit 15d6cbc

Browse files
committed
Implement post fix evaluation
1 parent e2fe686 commit 15d6cbc

2 files changed

Lines changed: 36 additions & 2 deletions

File tree

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
+ stack
22
+ next greater element
3-
+ postfix evaluation
4-
+ balanced parentheses
3+
+ balanced parentheses
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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

0 commit comments

Comments
 (0)