-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
57 lines (56 loc) · 1.32 KB
/
Copy pathindex.js
File metadata and controls
57 lines (56 loc) · 1.32 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
50
51
52
53
54
55
56
57
function precedence(operator) {
if (operator == "^") {
return 3;
} else if (operator == "*" || operator == "/") {
return 2;
} else if (operator == "+" || operator == "-") {
return 1;
} else {
return -1;
}
}
function infixToPostfix(expression) {
let stack = [];
let result = "";
for (let i = 0; i < expression.length; i++) {
if (/[0-9a-z]+/i.test(expression[i])) {
result += expression[i];
} else if (
expression[i] == "(" ||
expression[i] == "{" ||
expression[i] == "["
) {
stack.push(expression[i]);
} else if (
expression[i] == ")" ||
expression[i] == "}" ||
expression[i] == "]"
) {
while (
stack[stack.length - 1] != "(" &&
stack[stack.length - 1] != "{" &&
stack[stack.length - 1] != "["
) {
result += stack[stack.length - 1];
stack.pop();
}
stack.pop();
} else {
while (
stack.length != 0 &&
precedence(expression[i]) <= precedence(stack[stack.length - 1])
) {
result += stack[stack.length - 1];
stack.pop();
}
stack.push(expression[i]);
}
}
while (stack.length != 0) {
result += stack[stack.length - 1];
stack.pop();
}
return result;
}
let testExp = "A+B(C^D-E)";
console.log(infixToPostfix(testExp));