CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Using our stack in a Reverse Polish Calculator

Let's employ our stack data structure to evaluate basic integer arithmetic, as if using a Reverse Polish Calculator.

Each integer read from lines of a file is pushed onto the stack, arithmetic operators pop 2 integers from the stack, perform some arithmetic, and push the result back onto the stack.


int evaluate_RPN(FILE *fp)
{
    char  line[BUFSIZ];
    int   val1, val2;

    while( fgets(line, sizeof(line), fp) != NULL ) {  
        if(line[0] == '#')
            continue;
        if(isdigit(line[0]) || line[0] == '-')
            push_item( atoi(line) );

        else if(line[0] == 'a') {
            val1 = pop_item();
            val2 = pop_item();
            push_item( val1 + val2 );
        }
        ....
        else if(line[0] == 'd') {
            val1 = pop_item();
            val2 = pop_item();
            push_item( val2 / val1 );
        }
        else
	    break;
    }
    return pop_item();
}


# Our input data:
12
3
add
5
div


hp35

 


CITS2002 Systems Programming, Lecture 19, p6, 3rd October 2023.