Class 4: Stacks
cis 335 Fall 2001 Barry Cohen What is a stack? n A stack is an ordered sequence of items, of which only the last (‘top’) item can be accessed n As in lists, each node contains some data (‘soap’ or ‘garlic’) n The data may also be numeric or other type (‘5’ or ‘true’)
cis 335 Fall 2001 Barry Cohen Last in, first out (LIFO) n This restriction on access is sometimes called LIFO - ‘last in, first out’ n Example: the dishes in a cafeteria n Question: Is a movie line a stack? Is it LIFO?
cis 335 Fall 2001 Barry Cohen Stack operations n createStack() n destroyStack() n bool isEmpty() n push(in newItem) Put an item onto the stack n pop(out topItem) Remove and return top item n top(out topItem) Return top item, but don’t remove it. (Is this operation necessary?)
cis 335 Fall 2001 Barry Cohen List or stack? n Can a list do everything a stack can do? n Can a stack do everything a list can do? n Compare the operations. n Which to use? The simplest which can do the job.
cis 335 Fall 2001 Barry Cohen Example: valid parentheses n It this a legal expression? ((a + b) / (c - d / 2) n First test: an even number of parens n It this a legal expression? ((a + (b / (c - d ) / 2) n Second test: equal number of open and close parens n It this a legal expression? (a + b) / c) - (d (e / 2)
cis 335 Fall 2001 Barry Cohen Use the ‘counting test’ n Get an intuition: open paren: +1 close paren: -1 n Start with 0 n Value must always be nonnegative n Must end with 0
cis 335 Fall 2001 Barry Cohen Test expression using a stack n Start with empty stack n Open paren: push n Close paren: pop n End with empty stack
cis 335 Fall 2001 Barry Cohen Problems with stack solutions n Evaluating algebraic equations n Parsing a computer language (like C) n Parsing human language (at least some of it) n Executing computer programs (including recursive ones)
cis 335 Fall 2001 Barry Cohen Evaluate a postfix expression n An expression like you find on HP calculator (also called ‘reverse Polish notation’ - RPN) n Evaluating infix is complicated n Evaluating postfix is easy n Solution: infix -> postfix evaluate postfix
cis 335 Fall 2001 Barry Cohen Keep it simple n Assume correct expression n Only binary operators (+, -, *, /). (No unary ‘-’, for example.) n Only left to right order (no ‘**’, for example). n Each number is a single digit (0-9)
cis 335 Fall 2001 Barry Cohen Evaluate postfix n Evaluate postfix: * n Algorithm: while (there’s still input) * see a number * push it * see an op * pop two numbers from stack * apply op * push result