


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



In this lecture we will use the ADT stack operations to solve the problem of evaluating simple arithmetic expressions. As is the case with using any ADT, we are not going to make any assumptions regarding the ADT’s implemen- tation. The strategy we will employ is to first convert the infix arithmetic expression to a postfix expression. The stack operations work more naturally with postfix expressions. Evaluating infix expression is a more involved prob- lem. For the purpose of this lecture we will restrict ourselves to the following binary operations: *, /, +, -, and %. Exponentiation and unary operators will be disallowed to make our lives somewhat easy! Here is a summary of our simplifying assumptions:
2 Evaluating Postfix Expressions
Here is the pseudocode algorithm that evaluates postfix expressions:
for (each token Ch in the expression) { if (Ch is an operand) Push value that operand Ch represents onto stack else // Ch is an operator named Op { //evaluate and push the result Operand2 = top of stack Pop the stack Operand1 = top of stack Pop the stack Result = Operand1 Op Operand Push Result onto stack } }
Upon termination of the algorithm, the value of the expression will be on the top of the stack.
3 Converting Infix to Postfix Expressions
Here is a high-level description of what we must do to convert an expression written in infix notation to one written in postfix notation.
// append to PE the operators remaining in the stack while (S is not empty) { PE = PE.(top of S) pop S }