In: Computer Science
implement the algorithm described in this chapter to convert a prefix expression to postfix form. involve the classes that programming problems 4 and 5 describe
This is to be written in C++. I cannot provide anymore information, I cannot provide any class information, etc. This is all the problem that book gave me. This is for Data Structures and algorithms.
//code
#include <iostream>
#include <stack>
using namespace std;
bool checkIfOperator(char x) {
switch (x) {
case '+':
case '-':
case '/':
case '*':
return true;
}
return false;
}
string PrefixToPostfix(string prefix) {
stack<string> s;
for (int i = prefix.size() - 1; i >= 0; i-=1) {
if (checkIfOperator(prefix[i])) {
string a = s.top(); s.pop();
string b = s.top(); s.pop();
string temp = a + b + prefix[i];
s.push(temp);
}
else {
s.push(string(1, prefix[i]));
}
}
return s.top();
}
int main() {
string prefix;
cin >> prefix;
cout << "Postfix : " << PrefixToPostfix(prefix);
return 0;
}