I have a function that's taking infix expressions and converting them to prefix expressions. Here's my code:
string infixToPrefix(string expression)
{
stack<char> S; //holds operators
stack<char>output; //display like in class
string prefix = "";
char ch;
S.push('#');
for (int i = expression.length(); i > 0; i--){
ch = expression[i];
if (isOperand(ch) == true){
output.push(ch);
}
else {
if (ch == '('){
while (S.top() != ')'){
output.push(S.top());
S.pop();
}
}
else {
while (isp(S.top()) > icp(ch)){
output.push(S.top());
S.pop();
}
S.push(ch);
}
}
}
while (S.top() != '#'){
output.push(S.top());
S.pop();
}
while (!output.empty()){
if (output.top() == ')'){
output.pop();
}
else{
prefix.append(1,output.top());
output.pop();
}
}
return prefix;
}
This function has worked well with the sample expressions my professor wants me to use; "3-4-5" yields "--345" and "5*(4/2)" yields "*5/42". However, this does not work with the expression "3^4^5". It keeps giving me "^^345" where its supposed to be "^3^45".
Is my algorithm incorrect? Or could this have something to do with the ICP and ISP (in the code she gave me, both have "^" = 3.)?