Download presentation
Presentation is loading. Please wait.
1
Class 4: Stacks
2
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’)
3
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?
4
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?)
5
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.
6
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)
7
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
8
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
9
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)
10
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
11
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)
12
cis 335 Fall 2001 Barry Cohen Evaluate postfix n Evaluate postfix: 2 3 5 + * n Algorithm: while (there’s still input) * see a number * push it * see an op * pop two numbers from stack * apply op * push result
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.