-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfixToPostfix.js
More file actions
49 lines (44 loc) · 1.55 KB
/
infixToPostfix.js
File metadata and controls
49 lines (44 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const operators = ['+', '-', '*', '/', '(', ')', '^']
const priority = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3 }
function infixToPostfix(expression) {
let open = 0
let closed = 0
const stack = []
const output = []
expression.forEach((character) => {
if (!operators.includes(character)) {
output.push(character)
}
else if (character === '(') {
stack.push('(')
open += 1
}
else if (character === ')') {
while (stack.length > 0 && stack[stack.length - 1] !== '(') {
output.push(stack.pop())
closed += 1
}
stack.pop()
}
else {
while (stack.length > 0 && stack[stack.length - 1] !== '(' && priority[character] <= priority[stack[stack.length - 1]]) {
output.push(stack.pop())
}
stack.push(character)
}
})
while (stack.length > 0) {
output.push(stack.pop())
}
console.log('stack after conversion: ', stack)
console.log('Parens: open, closed: ', open, closed)
return output.join(' ')
}
const testInput = ['8', '^', '2', '+', '6', '-', '2', '*', '10', '/', '2']
const postFixExpression = infixToPostfix(testInput)
console.log('testInput: ', testInput.join(' '))
console.log('postfix: ', postFixExpression)
const testInput2 = ['1', '+', '(', '(', '2', '*', '8', ')']
const postFixExpression2 = infixToPostfix(testInput2)
console.log('testInput2: ', testInput2.join(' '))
console.log('postfix2: ', postFixExpression2)