Postfix - int expr_entry = 0; while (! expr.isEmpty() ) {...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
#include <iostream> #include <cassert> #include "LinkedList.h" using namespace std ; /* If we only use the addToFront and removeFromFront methods our * LinkedList class behaves like a Stack. We can use a stack to evaluate postfix expressions in a straightforward manner. Consider the following: ((1+3)+2)*(6*(9-2)) It is equivalent to 1 3 + 2 * 6 9 2 - * + in postfix form. Evaluation of postfix expressions is easy using a stack. We can evaluate postfix expressions on an integer stack assuming that -1 --> + -2 --> - -3 --> * */ int main() { LinkedList expr ; expr.addToBack(1) ; expr.addToBack(3) ; expr.addToBack(-1) ; expr.addToBack(2) ; expr.addToBack(-3) ; expr.addToBack(6) ; expr.addToBack(9) ; expr.addToBack(2) ; expr.addToBack(-2) ; expr.addToBack(-3) ; expr.addToBack(-1) ; LinkedList stack ; cout << "The expr is: " << expr << endl ; cout << "The stack is: " << stack << endl ; cout << "-----------------------------------" << endl ;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: int expr_entry = 0; while (! expr.isEmpty() ) { expr_entry = expr.removeFromFront() ; if (expr_entry >= 0) { // It is a value stack.addToFront (expr_entry) ; } else { // It is an operator assert (! stack.isEmpty() ); int v2 = stack.removeFromFront() ; assert (! stack.isEmpty() ); int v1 = stack.removeFromFront() ; int op = expr_entry ; assert (op < 0); int result = 0; switch (op) { case -1: // Add result = v1 + v2 ; break ; case -2: // Subtract result = v1 - v2 ; break ; case -3: // Multiply result = v1 * v2 ; break ; } stack.addToFront(result) ; } cout << "The expr is: " << expr << endl ; cout << "The stack is: " << stack << endl ; cout << "-----------------------------------" << endl ; } assert (! stack.isEmpty() ); int result = stack.removeFromFront() ; cout << "The value is : " << result << endl ; }...
View Full Document

This note was uploaded on 10/28/2010 for the course CSCI 1113 taught by Professor Staff during the Spring '08 term at Minnesota.

Page1 / 2

Postfix - int expr_entry = 0; while (! expr.isEmpty() ) {...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online