COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

Stacks My Stack Program
StackInterface.java
MyArrayListStack.java
MyArrayListStackProjectClient.java
EmptyStackException.java
Postfix Program Palindrome Program



Postfix Program


Description

This program uses a stack to evaluate a postfix expression and calculate the result.

Associated Concepts:

Stack

Algorithm:

main method:

Create a stack object.

Input a postfix expression with a blank space to separate each token.

Split each token into an array.

In a loop, retrieve each token from the array.

If the token is an operator (+, -, *, /):

Pop two objects from the stack.

Call calculate() method to get the result.

Push the result back to the top of the stack.

Otherwise (the token is an operand):

Push it to the top of the stack.

After the loop is ended, print the result.

calculate method definition:

Use a switch structure to calculate the result based on the operator.

Return the result.

Source Code



Sample Run



Video