Data Structure Stack: Infix to Postfix

时间:2023-03-10 06:11:28
Data Structure Stack: Infix to Postfix

http://geeksquiz.com/stack-set-2-infix-to-postfix/

 #include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <fstream>
#include <map>
#include <set>
using namespace std; bool isoprand(char x) {
return x >= 'A' && x <= 'Z' || x >= 'a' && x <= 'z';
} int prec(char x) {
if (x == '+' || x == '-') return ;
if (x == '*' || x == '/') return ;
if (x == '^') return ;
return -;
} int infixtopostfix(string s) {
string ans;
stack<char> T;
for (int i = ; i < s.size(); i++) {
if (isoprand(s[i])) ans += s[i];
else if (s[i] == '(') T.push(s[i]);
else if (s[i] == ')') {
while (!T.empty() && T.top() != '(') {
ans += T.top();
T.pop();
}
if (!T.empty() && T.top() != '(') return -;
T.pop();
}
else {
while (!T.empty() && prec(s[i]) <= prec(T.top())) {
ans += T.top();
T.pop();
}
T.push(s[i]);
}
}
while (!T.empty()) {
ans += T.top();
T.pop();
}
cout << ans << endl;
} int main() {
string s = "a+b*(c^d-e)^(f+g*h)-i";
infixtopostfix(s);
return ;
}