BUPT-homework/semester3/pset1/7-2-Infix-to-Postfix-Conversion.cpp

95 lines
1.7 KiB
C++
Raw Permalink Normal View History

2022-10-08 09:33:48 +08:00
// Convert the infix expression to postfix expression.
#include <cctype>
#include <cstdio>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int prec(char ch) {
if (ch == '+' || ch == '-') {
return 0;
} else if (ch == '*' || ch == '/') {
return 1;
} else {
2022-10-14 18:47:09 +08:00
// the precidence is the lowest, to make sure it stays in the stack.
// calculate stuff outside the paren last
return -1;
2022-10-08 09:33:48 +08:00
}
}
void printEval(string &postfix) {
stack<double> st;
double l, r;
double ans;
for (char ch : postfix) {
if (isdigit(ch)) {
st.push(ch - '0');
} else {
r = st.top();
st.pop();
l = st.top();
st.pop();
if (ch == '+') {
ans = l + r;
} else if (ch == '-') {
ans = l - r;
} else if (ch == '*') {
ans = l * r;
} else if (ch == '/') {
ans = l / r;
}
st.push(ans);
}
}
printf("%.2lf\n", st.top());
}
void printFix(string &postfix) {
for (char ch : postfix) {
printf("%c ", ch);
}
}
int main(void) {
string input;
cin >> input;
stack<char> st;
string postfix;
for (char ch : input) {
if (isdigit(ch)) {
postfix.push_back(ch);
} else {
// if is not a digit
if (ch == '(') {
st.push(ch);
} else if (ch == ')') {
while (st.top() != '(') {
postfix.push_back(st.top());
st.pop();
}
st.pop();
} else {
// a operand
while (!st.empty() && prec(ch) <= prec(st.top())) {
postfix.push_back(st.top());
st.pop();
}
st.push(ch);
}
}
}
while (!st.empty()) {
postfix.push_back(st.top());
st.pop();
}
printEval(postfix);
printFix(postfix);
return 0;
}