-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinfix-to-postfix-using-stack.js
More file actions
62 lines (55 loc) · 1.28 KB
/
infix-to-postfix-using-stack.js
File metadata and controls
62 lines (55 loc) · 1.28 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
58
59
60
61
62
function prec(sym) {
switch (sym) {
case '^':
return 3;
case '/':
case '*':
return 2;
case '+':
case '-':
return 1;
default:
return -1;
}
}
function infixToPostfix(str) {
let stack = [];
let result = '';
for (let i = 0; i < str.length; i++) {
let char = str[i]; // all the character of the expression copied here;
if (
(char >= 'a' && char <= 'z') ||
(char >= 'A' && char <= 'Z') ||
(char >= '0' && char <= '9')
)
result += char;
else if (char === '(') stack.push('(');
else if (char === ')') {
while (stack[stack.length - 1] !== '(') {
result += stack[stack.length - 1];
stack.pop();
}
stack.pop();
} else {
while (
stack.length !== 0 &&
prec(str[i]) <= prec(stack[stack.length - 1])
) {
result += stack[stack.length - 1];
stack.pop();
}
stack.push(char);
}
}
while (stack.length !== 0) {
result += stack[stack.length - 1];
stack.pop();
}
return result;
}
let exp = 'A+(B*C-(D/E)*G)*H';
const result = infixToPostfix(exp);
console.log(result);
/*
The less than or equal operator (<=) returns true if the left operand is less than or equal to the right operand, and false otherwise
*/