Skip to content

postfix-expression evaluation problem #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 5, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/_DataStructures_/Stack/postfix-expression-evaluation/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Evaluation of Postfix Expression
* Input:456*+
* Output:34
*/

const Stack = require('../index');

function evaluatePostfixExpression(expression) {
let s = new Stack();
for (let i = 0; i < expression.length; i++) {
const char = expression[i];
if (!isNaN(char)) {
//if number push the char onto stack
s.push(Number(char));
} else {
// if char is an operator then pop two elements from stack, evaluate them accordingly based on operator.
//push the result to stack
let val1 = s.pop();
let val2 = s.pop()
switch (char) {
case '+':
s.push(val2 + val1);
break;
case '-':
s.push(val2 - val1);
break;
case '*':
s.push(val2 * val1);
break;
case '/':
s.push(val2 / val1);
break;

}
}
}
//pop the value of postfix expression
return s.pop();
}

console.log(evaluatePostfixExpression("123+*8-")); // -3

console.log(evaluatePostfixExpression("12345*+*+")); // 47