Last active
June 14, 2018 16:56
-
-
Save pinkmomo027/e180d61d8874a0e1b9902d28f2668222 to your computer and use it in GitHub Desktop.
infix to postfix, without parenthesis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Author
pinkmomo027
commented
Jun 14, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment