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