Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 28dee28

Browse files
postfix-expression evaluation problem
1 parent 80d5d72 commit 28dee28

File tree

1 file changed

+44
-0
lines changed
  • src/_DataStructures_/Stack/postfix-expression-evaluation

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /