Skip to content

Instantly share code, notes, and snippets.

@pinkmomo027
Last active June 14, 2018 16:56
Show Gist options
  • Save pinkmomo027/e180d61d8874a0e1b9902d28f2668222 to your computer and use it in GitHub Desktop.
Save pinkmomo027/e180d61d8874a0e1b9902d28f2668222 to your computer and use it in GitHub Desktop.
infix to postfix, without parenthesis
// a + b * c + d
// a b c * + d +
// a + b * c + d
// a b c * + d +
function infixToPostfix(input) {
let stack = [], answer = [], char;
const operands = {
'+' : 1,
'-' : 1,
"*" : 2,
"/" : 2,
};
for(let i = 0; i < input.length; i++ ) {
char = input.charAt(i);
let currentPrecedence = operands[char];
if (currentPrecedence) {
let peek = operands[stack[stack.length - 1]];
// pop until the peek is smaller
while(peek >= currentPrecedence) {
answer.push(stack.pop());
peek = operands[stack[stack.length - 1]];
}
stack.push(char);
} else { // not operand, push to answer
answer.push(char);
}
}
while(stack.length > 0) {
answer.push(stack.pop())
}
return answer.join('');
}
function executePostfix(str) {
let stack = [], char, operand1, operand2, tempOperand;
let operators = [ '+', '-', '*', '/'];
for(let i = 0; i < str.length; i++) {
char = str.charAt(i);
if (operators.indexOf(char) >= 0) {
// operate
operand2 = stack.pop();
operand1 = stack.pop();
tempOperand = eval(operand1+char+operand2);
stack.push(tempOperand);
} else {
stack.push(char);
}
}
return stack.pop();
}
// let p = infixToPostfix('a+b*c+d');
let p = infixToPostfix('2+3*3+7');
let answer = executePostfix(p);
console.log(p, answer);
@pinkmomo027
Copy link
Author

233*+7+ 18
[Finished in 0.1s]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment