1
$\begingroup$

I have been given a question about a stack program which I can not solve.

Write a stack program to evaluate the term

$\qquad (((A+B)-(A*B))*C)/(((A-B-C))⁄2)$

How do I approach this problem?

$\endgroup$
11
  • 4
    $\begingroup$ Hint: Check for reverse polish notation $\endgroup$ Commented Mar 28, 2013 at 8:21
  • $\begingroup$ what is the reverse polish notation? it is important ? $\endgroup$
    – fttamy
    Commented Mar 28, 2013 at 8:24
  • 1
    $\begingroup$ hint: it might help to change the representation of the equation before feeding it to your program $\endgroup$
    – collapsar
    Commented Mar 28, 2013 at 8:52
  • $\begingroup$ may be if i put A=3,B=2,C=4 Then first i find the (A+B)-(A*B)*C = R1 $\endgroup$
    – fttamy
    Commented Mar 28, 2013 at 9:06
  • 1
    $\begingroup$ hint: try a simpler equation first. heed bartek's advice. $\endgroup$
    – collapsar
    Commented Mar 28, 2013 at 10:36

1 Answer 1

1
$\begingroup$

What you want to do is; either first translate the expression into something that is easier for a stack machine to handle (like reverse polish).

The other is to use a modified shunting yard algorithm which can handle parenthesis.

You have 2 stacks: a result stack that holds the numbers where you push the numbers as you encounter them;

and an operator stack that holds operators in decreasing priority order.

When you need to add a operator that is of lower precedence you pop from the operator stack. Then apply that operator to the top 2 values on the result stack and replace them with the result. A parenthesis is of lowest priority but is the only one that can go on top of a higher priority operator.

When you encounter a closing parenthesis you pop from the operator stack and apply to the result stack until you find a closing parenthesis which you pop.

$\endgroup$
2
  • 2
    $\begingroup$ Please try to adhere to common styling courtesy, e.g. punctuation and capitalisation. $\endgroup$
    – Raphael
    Commented Mar 28, 2013 at 12:02
  • $\begingroup$ i still not understand $\endgroup$
    – fttamy
    Commented Mar 31, 2013 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.