Stacks

A list data structure

Stacks  -

•      A list structure in which the elements are added and removed from the top only

•      The last element to be added is the first one off the stack

•      called a LIFO (last in, first out) data structure

 

Stack Applications

·        Reverse a string

·        Test for balanced parentheses

·        Evaluating postfix expressions

·        Converting from infix to postfix

·        The system stack pushes the return address in method calls

 

Checking for balanced parentheses

Push opening (, pop closing ); if there is anything left of the stack at the end of the string, they are unbalanced

(a + b * (c / (d - e) ) ) + (d / e)

 

Infix and Postfix

•      Infix

–   the operator is between the operands

–   may require parentheses to specify order

–   several ways to express the same thing (not unique)

•      Postfix

–   the operator follows the two operands

–   eliminates the need for parentheses

•      The compiler converts all infix expressions to postfix to evaluate them

 

Evaluating Postfix

•      rules are much simpler than infix

–    The operator applies to the two operands that immediately precede it

•      no operator precedence rules

•      no parentheses

•      evaluate left to right

•      the expression is unique

•      The simplest way to evaluate is to use a stack

 

Postfix examples

•       6  2 / 5 +

•        4  5 + 7  2 - *

 

Simple algorithm to evaluate postfix

•      if a number, push onto the stack

•      if operator, pop two numbers, apply operator

•      push result onto the stack

•      Examples

    4  5  +  7  2  -  *

6  5  2  3  +  8  *  + 3  +  * 

 

Converting infix to postfix

•      The operator applies to the two operands that immediately precede it

•      Convert a+b*c

•      Convert (a+b)*c

•      Notice

–   The operands always stay in the same order with respect to each other

–   An operator will move only “to the right” with respect to the operands

–   All parentheses are removed

 

Converting to infix to postfix using a stack

•      Read each character in the expression

•      If the character is a operand, output it

•      If the character is an operator or parentheses …4 cases:

–   It is an opening parentheses

–   It is of higher precedence than the top of the stack

–   It is of lower precedence than the top of the stack

–   It is a closing parentheses

 

What to do with the cases

–   Push it onto the stack if:

•   The character read  is of higher precedence than the top of the stack

•   It is an opening parentheses

–   Otherwise pop

•   If the top of the stack is a closing parentheses pop and output until you reach the opening parentheses

•   If the character read is of lower precedence than the top of the stack

–   Pop the stack and output until the top of stack the is lower precedence than the character read, then push the character read.