-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfix_To_Postfix.cpp
More file actions
70 lines (61 loc) · 1.73 KB
/
Infix_To_Postfix.cpp
File metadata and controls
70 lines (61 loc) · 1.73 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
63
64
65
66
67
68
69
70
#include<bits/stdc++.h>
using namespace std;
int getPriority(char ch) {
if(ch == '+' || ch == '-') return 1;
else if(ch == '*' || ch == '/') return 2;
else if(ch == '^') return 3;
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || (ch == '.')) return 0;
else return -1;
}
string infixToPostFix(string infix) {
stack<char>stk;
int i = 0;
string postfix = "";
for(i = 0; infix[i]; i++) {
char ch = infix[i];
if(ch == '(') stk.push(ch);
else if(ch == ')') {
while(!stk.empty() && stk.top() != '(') {
postfix += stk.top();
postfix += ',';
stk.pop();
}
stk.pop();
}
else {
int priority = getPriority(ch);
if(priority == 0) {
while(getPriority(infix[i]) == 0) {
postfix += infix[i];
i++;
}
i--;
postfix += ',';
}
else {
if(stk.empty()) stk.push(ch);
else {
while(!stk.empty() && stk.top() != '(' && (priority <= getPriority(stk.top()))) {
postfix += stk.top();
postfix += ',';
stk.pop();
}
stk.push(ch);
}
}
}
}
while(!stk.empty()) {
postfix += stk.top();
postfix += ',';
stk.pop();
}
postfix.erase(postfix.end()-1);
return postfix;
}
int main() {
string infix = "A+(180.5*C-(D/E^F)*G)*2.0";
string postfix = infixToPostFix(infix);
cout << postfix << endl;
return 0;
}