Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
- [Baseball Game](src/_DataStructures_/Stack/baseball-game)
- [Minimum Stack](src/_DataStructures_/Stack/min-stack)
- [Balanced Parenthesis](src/_DataStructures_/Stack/balanced-parenthesis)
- [Postfix Expression Evaluation](src/_DataStructures_/Stack/postfix-expression-evaluation)


- [Queue](src/_DataStructures_/Queue)
- [Weave](src/_DataStructures_/Queue/weave)
Expand Down
40 changes: 40 additions & 0 deletions src/_DataStructures_/Stack/postfix-expression-evaluation/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
* 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();
}