Activity: Evaluating the Postfix Expression

Scenario

We are used to writing mathematical expressions in the form of 1 + 2 * 3. This type of notation is called an infix. Using infix notation, an operator is always in between two operators. There is a different notation called postfix, where the operator is after the operands. Examples of such expressions are shown in the following table:

Infix expression Postfix expression
1 + 2 1 2 +
1 + 2 * 3 1 2 3 * +
(1 + 2) * 3 1 2 + 3 *
5 + 4 / 2 * 3 5 4 2 / 3 * +

 

Aim

Implement an algorithm that accepts a postfix string, evaluates it, and returns the result.

Prerequisites

 public double evaluate(String postfix) 
  • Assume the operator and operands are always separated by a space, such as "5 2 +". The input string will look like the examples shown in the preceding table.
If you have your project set up, you can run the unit test for this activity by running the following command:

gradlew test --tests com.packt.datastructuresandalg.lesson2.activity.postfix*

The solution becomes a lot simpler if you use one of the data structures we studied in this section.

Steps for Completion

  1. Use the stack data structure to solve this problem
  2. Start processing the expression from left to right
  3. If you encounter a numeric operand, push it on the stack
  4. If you encounter an operator, pop two items from the stack and perform the operation accordingly (addition, subtraction, and so on) and push the result back on the stack
  5. Once you have processed the entire expression, the result should be the on the top of the stack
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.152.139