Can anyone show me a good algorithm for multiplication,division,addition and subtraction using stacks?I've seen quite a lot of algorithms,but they all have the same problem.For example,if the expression is 5+4*2 , the program sees that * needs to be done first , so it puts everything on the stacks so it looks like this:
2
4 *
5 +
val op
while (!op.empty())
{
int num1 = val.top();
char operator = op.top();
val.pop();
int num2 = val.top();
val.pop();op.pop();
stack.push(calculate(num2,num1,sign));
//where calcu late is a function that returns the result of that operation
}
But if the expression looks like this:3 - 4*4 + 5*3,the stack will be:
15
16 +
3 -
val op
so it will do 15 + 16 - 3 , which is 28 , instead of :3 - 16 + 15 = 2. Can anyone provide me a good algorithm using stacks?Thanks!