-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.dart
More file actions
57 lines (52 loc) · 1.28 KB
/
InfixToPostfix.dart
File metadata and controls
57 lines (52 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
import 'dart:io';
bool isOperator(String c) {
return ['+', '-', '*', '/', '^'].contains(c);
}
bool isOperand(String c) {
return RegExp(r"^[0-9]$").hasMatch(c);
}
int precedence(String op) {
if (op == '+' || op == '-') {
return 1;
}
if (op == '*' || op == '/') {
return 2;
}
if (op == '^') {
return 3;
}
return 0;
}
String infixToPostfix(String expression) {
List<String> stack = [];
String postfix = '';
for (var char in expression.runes) {
String c = String.fromCharCode(char);
if (c == '(') {
stack.add(c);
} else if (c == ')') {
while (stack.isNotEmpty && stack.last != '(') {
postfix += stack.removeLast();
}
stack.removeLast(); // pop '('
} else if (isOperator(c)) {
while (stack.isNotEmpty &&
precedence(stack.last) >= precedence(c) &&
stack.last != '(') {
postfix += stack.removeLast();
}
stack.add(c);
} else if (isOperand(c)) {
postfix += c;
}
}
while (stack.isNotEmpty) {
postfix += stack.removeLast();
}
return postfix;
}
void main() {
String infixExpression = stdin.readLineSync()!;
String postfixExpression = infixToPostfix(infixExpression);
print("$postfixExpression");
}