Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks Chapter 5. Overview n The stack ADT n Exceptional situations n Stack implementations stacks in Javastacks in Java.

Similar presentations


Presentation on theme: "Stacks Chapter 5. Overview n The stack ADT n Exceptional situations n Stack implementations stacks in Javastacks in Java."— Presentation transcript:

1 Stacks Chapter 5

2 Overview n The stack ADT n Exceptional situations n Stack implementations stacks in Javastacks in Java

3 What is a Stack? n Linear pile of objects of one type one on top of another; not a “heap”one on top of another; not a “heap” in a particular orderin a particular order access only at one end (the “top”)access only at one end (the “top”) “LIFO”: Last In = First Out“LIFO”: Last In = First Out n Real life stacks stack of books/paperstack of books/paper stack of plates/bowls/beer cupsstack of plates/bowls/beer cups

4 Stack Operations n Stacks require at least these operations: insert at top (push).push(item)insert at top (push).push(item) delete from top (pop, pull).pop()delete from top (pop, pull).pop() n Typically have some others check if empty.isEmpty()check if empty.isEmpty() inspect top element (peek, top).peek()inspect top element (peek, top).peek() empty it out.clear()empty it out.clear() get number of elements.size()get number of elements.size()

5 A Stack n Generally arranged up & down top at the toptop at the top n Old items are popped off the stack myStack.pop()myStack.pop() n New items are pushed onto the stack myStack.push(14)myStack.push(14) 35 24 81 12 5 7 17 12 8 Top Stack

6 A Stack n Generally arranged up & down top at the toptop at the top n Old items are popped off the stack myStack.pop()myStack.pop() n New items are pushed onto the stack myStack.push(14)myStack.push(14) 24 81 12 5 7 17 12 8 Top Stack

7 A Stack n Generally arranged up & down top at the toptop at the top n Old items are popped off the stack myStack.pop()myStack.pop() n New items are pushed onto the stack myStack.push(14)myStack.push(14) 14 24 81 12 5 7 17 12 8 Top Stack

8 Exercise n Draw the stacks that result from the following operations. Start with empty each time. Also, make a list of the items popped. push A, push B, push C, pop, push D, pop, poppush A, push B, push C, pop, push D, pop, pop push 1, push 2, pop, pop, push 3, push 4, poppush 1, push 2, pop, pop, push 3, push 4, pop push 1, push 2, push 3, push 4, pop, pop, pop, poppush 1, push 2, push 3, push 4, pop, pop, pop, pop

9 Return Values n Push naturally void put this thing on the stack; nothing to returnput this thing on the stack; nothing to return n Peek naturally value-returning return value that is on top of stackreturn value that is on top of stack n Empty naturally boolean (empty or not?) n Clear naturally void n Size naturally value-returning number of items in the stacknumber of items in the stack

10 Return Values n Pop can be either void or value-returning either: take something off stack and discard iteither: take something off stack and discard it »C++’s STL stack is like this or: take something off stack and return itor: take something off stack and return it »Java’s java.util.Stack like this n Pop must return value if no peek operation otherwise no way to get values out of the stack!otherwise no way to get values out of the stack! we (text authors and I) prefer value-returningwe (text authors and I) prefer value-returning

11 Exceptional Circumstances n What could go wrong? try to pop off/peek at top of empty stacktry to pop off/peek at top of empty stack try to push onto a full stacktry to push onto a full stack try to add null to stack (is this wrong?)try to add null to stack (is this wrong?) n Options to deal are same as with bags return false (if naturally void)return false (if naturally void) return special value (if one is available)return special value (if one is available) throw exception (checked or unchecked?)throw exception (checked or unchecked?)

12 Design Decisions n Push is naturally void have it return false for failure?have it return false for failure? have it throw an exception?have it throw an exception? n Peek is naturally value-returning have it return null for failure?have it return null for failure? have it throw an exception?have it throw an exception? n Pop can be either! boolean/null/exception all valid options!boolean/null/exception all valid options!

13 Exceptions: Checked or Not? n Client can easily check if stack is empty there’s a method for thatthere’s a method for that n Client can thus write code that will never try to pop/peek on empty stack n Client should not be made to deal with exceptions n Use unchecked exceptions

14 Unchecked Exc n s & Interfaces n Unchecked exceptions don’t need to be mentioned in the interface n If they are mentioned, they may be ignored! implementing classes don’t need to throw themimplementing classes don’t need to throw them »NOTE: checked exceptions cannot be ignored n Interface should specify them anyway at least in the javadoc!at least in the javadoc! clients should know what to expectclients should know what to expect

15 More Design Decisions n Provide multiple versions? methods must have different namesmethods must have different names »can’t have different parameters! »pair names in some way two versions return null?two versions return null? two versions throw exceptions?two versions throw exceptions? n How many different versions? don’t want things to be too complexdon’t want things to be too complex

16 My Decisions n Push not expected to fail false return value might be missed…false return value might be missed… …so throw an IllegalStateException…so throw an IllegalStateException n Two versions of pop method pop throws a NoSuchElementExceptionpop throws a NoSuchElementException pull returns null when stack is emptypull returns null when stack is empty n Two versions of peek method top throws a NoSuchElementExceptiontop throws a NoSuchElementException peek returns null when the stack is emptypeek returns null when the stack is empty

17 My Stack Interface public interface MyStackInterface { public void push(T newEntry); public void push(T newEntry); // throws IllegalStateException public T pop(); // throws NoSuchElementException public T pop(); // throws NoSuchElementException public T top(); // throws NoSuchElementException public T top(); // throws NoSuchElementException public T pull();// may return null public T pull();// may return null public T peek(); // may return null public T peek(); // may return null public boolean isEmpty(); public boolean isEmpty();}

18 Other Stack Interfaces/Classes StackInterface (from Text) void push(T newEntry); // nothing! T pop(); // throws EmptyStackExc n. // throws EmptyStackExc n. T peek(); // throws EmptyStackExc n. java.util.Deque (*) void push(T newEntry); // throws IllegalStateExc n. // throws ClassCastExc n. // throws NullPointerExc n. // throws IllegalArgumentExc n. T pop(); // throws NoSuchElementExc n. T peek(); // may return null (class) java.util.Stack T push(T newEntry); // nothing T pop(); // throws EmptyStackExc n. T peek(); // throws EmptyStackExc n. (*) Deque is preferred to Stack!

19 Using Stacks n Balancing brackets n Pre/postfix expressions n Conversion to pre/postfix from infix (“normal”) n Procedure Activation Records n Towers of Hanoi n Railway shunting n Circuit design n Equivalence classes n Maze tracing

20 Balancing Brackets n Want to know if a string has the right number of closing brackets/parentheses/etc. n Each closing item must match opening item ] for [, ) for (, etc.] for [, ) for (, etc. n Nesting may be involved “{a(1, 2), b([c, d]), {e, f, [(g), ((h))]}}”“{a(1, 2), b([c, d]), {e, f, [(g), ((h))]}}” “(1, [2, 3, ([4, (5, 6), {7,8})])])”“(1, [2, 3, ([4, (5, 6), {7,8})])])”

21 Method n Scan the string one character at a time stack up opening brackets as you see themstack up opening brackets as you see them when you see a closing bracket, pop a bracket off the top & make sure it matcheswhen you see a closing bracket, pop a bracket off the top & make sure it matches n Return false if: try to pop from an empty stacktry to pop from an empty stack popped bracket doesn’t matchpopped bracket doesn’t match procedure ends with non-empty stackprocedure ends with non-empty stack

22 Code for i  1.. Length(string) if isOpenBracket(string[i]) stack.push(string[i]); else if isCloseBracket(string[i]) if stack.isEmpty() return false; if ~match(stack.top(), string[i]) return false; stack.pop(); return stack.isEmpty();

23 Trace Execution n “{a(1, 2), b([c, d]), {e, f, [(g), ((h))]}}” { ({({ { ({({ [({[({ ({({ { {{{{ [{{[{{ ([{{([{{ [{{[{{ ([{{([{{ (([{{(([{{ ([{{([{{ [{{[{{ {{{{ { {()([]){[()(())]}} {a(1, 2), b([c, d]), {e, f, [(g), ((h))]}} Stack is empty: return true

24 Trace Execution n “(1, [2, 3, ([4, (5, 6), {7,8})])])” ( [([( ([(([( [([([([( ([([(([([( [([([([( {[([({[([( [([([([( ([([(){}) (1, [2, 3, ([4, (5, 6), {7,8})])]) Mismatch: return false

25 Exercise n Trace the balancing method for the following string: (1 + (12 * [1, 3, 5], )) [, 7, 87, ][]()){()}(1 + (12 * [1, 3, 5], )) [, 7, 87, ][]()){()}

26 Postfix Calculator n AKA Reverse Polish notation used on HP calculatorsused on HP calculators n No need for parentheses (3 + 5)*(8 + 17*6) becomes 3 5 + 8 17 6 * + *(3 + 5)*(8 + 17*6) becomes 3 5 + 8 17 6 * + * n Number, enter, number, operation 5 (enter) 17 (times) [85 appears]5 (enter) 17 (times) [85 appears]

27 Method n Numbers get pushed n Operators: pop top two elementspop top two elements do math according to operationdo math according to operation push resultpush result

28 Trace Execution n 3 5 + 8 17 6 * + * 3 5353 8 8888 17 8 6 17 8 102 8 110 8 35+8176*+* 880 (3 + 5)*(8 + 17*6) = 8*(8 + 102) = 8*110 = 880

29 Exercise n Evaluate the following post-fix expression 1 2 3 4 5 + * + * 10 / show your stackshow your stack show the equivalent infix expressionshow the equivalent infix expression

30 Conversion to Postfix n Write down operators & operations the way they need to be done used to compile expressionsused to compile expressions n (3 + 5)*(8 + 17*6) 3+5 first  3, 5, +3+5 first  3, 5, + 17*6 next  17, 6, *17*6 next  17, 6, * 8 + (17*6)  8, 17, 6, *, +8 + (17*6)  8, 17, 6, *, + multiply above  3, 5, +, 8, 17, 6, *, +, *multiply above  3, 5, +, 8, 17, 6, *, +, *

31 Things to Note n (3 + 5)*(8 + 17*6)  3 5 + 8 17 6 * + * order of operations  17*6 instead of 8 + 17order of operations  17*6 instead of 8 + 17 parentheses  3+5 instead of 5*8parentheses  3+5 instead of 5*8 numbers written down in same ordernumbers written down in same order n Need to keep operations pending next operation may need to be done before itnext operation may need to be done before it closing parenthesis  complete all ops since (closing parenthesis  complete all ops since (

32 Trace of Conversion n (3 + 5) * (8 + 17 * 6 – 2) ( +(+( (*(* +(*+(* *+(**+(* * (3+5) ( + (8*17*6–)\0 35 * + –(*–(* 2 8176 +(*+(* * (*(* + 2 (*(* – *

33 Exercise n Write pseudo-code for the infix to postfix conversion what functions would be useful?what functions would be useful? so use them!so use them! hint: tokens – isNum(token), isOp(token)hint: tokens – isNum(token), isOp(token) token is a number (int) or operator (char)token is a number (int) or operator (char)

34 Stack Implementations n Can use arrays or linked structures n Top is the important location for arrays it’s at the back (of the used part)for arrays it’s at the back (of the used part) for linked structures it’s at the frontfor linked structures it’s at the front both very much like a Bagboth very much like a Bag »but we only never need to remove the latest object »just like how we did remove() at first

35 Stacks in Java n Use Deque instead of Stack import and declare (like Lists, Sets, Bags, …)import and declare (like Lists, Sets, Bags, …) import java.util.Deque; import java.util.ArrayDeque; Deque stack = new ArrayDeque (); Deque stack = new ArrayDeque (); n Deques have more operations than stacks use only the Stack operations!use only the Stack operations! push/pop may throw exceptionspush/pop may throw exceptions peek may return nullpeek may return null

36 Questions


Download ppt "Stacks Chapter 5. Overview n The stack ADT n Exceptional situations n Stack implementations stacks in Javastacks in Java."

Similar presentations


Ads by Google