1

I have found conversion from infix to prefix and am trying to follow it but am having trouble. I have most of it, but am having trouble comparing operator hierarchy. Example compare \ to *. * get has higher hierarchy. Here is the code. I put ?? around the part I am having trouble with. The language I am using is c++.

    string s;
stack<char>operatorStack;
stack<char>operandStack;
char rightOperand;
char leftOperandd;
char operand;
char opera
s = "1 + 2 * ( 1 - 2 - 3 - 4 ) ";


for (int i=0; i<s.length(); i++) {
    if (s[i]!=' ') {
            int arr= s[i];
        cout << arr<<" ";
        if (arr>=48) {
            operandStack.push(s[i]);
        }else {
            if (s[i]=='(' || operatorStack.empty()||??(OperatorHierarchy(token) > OperatorHierarchy(OperatorStack.Top()) )??
                operandStack.push(s[i]);
            else if(s[i]==')'){
                while (operandStack.top()!='(') {
                    opera=operatorStack.top();
                    operatorStack.pop();
                    rightOperand=operandStack.top();
                    operandStack.pop();
                    leftOperandd=operandStack.top();
                    operandStack.pop();
                    operand=opera+rightOperand+leftOperandd;
                    operandStack.push(operand); 
                }
                operatorStack.pop();
            }else if (?? operator hierarchy of token is less than or equal to hierarchy of top of the operator stack  ??) {
                while (!operatorStack.empty() && ??OperatorHierarchy(token) lessThen Or Equal to OperatorHierarchy(OperatorStack.Top()) ) ?? ) {
                    opera=operatorStack.top();
                    operatorStack.pop();
                    rightOperand=operandStack.top();
                    operandStack.pop();
                    leftOperandd=operandStack.top();
                    operandStack.pop();
                    operand=opera+rightOperand+leftOperandd;
                    operandStack.push(operand); 
                }
                operatorStack.push(s[i]);
            }

        }

    }

}
while (!operatorStack.empty()) {
    opera=operatorStack.top();
    operatorStack.pop();
    rightOperand=operandStack.top();
    operandStack.pop();
    leftOperandd=operandStack.top();
    operandStack.pop();
    operand=opera+rightOperand+leftOperandd;
    operandStack.push(operand); 
}
cout << operatorStack.top();
operatorStack.pop();

return 0;
}
Community
  • 1
  • 1
Aaron
  • 4,380
  • 19
  • 85
  • 141
  • 1
    Have you looked at the [Shunting-Yard algorithm](http://en.wikipedia.org/wiki/Shunting-yard_algorithm) on Wikipedia? – Cameron Nov 01 '11 at 02:26

0 Answers0