36
Stacks Stacks Chapter 5 Chapter 5

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

Embed Size (px)

Citation preview

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

StacksStacks

Chapter 5Chapter 5

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

OverviewOverview

The stack ADTThe stack ADT Exceptional situationsExceptional situations Stack implementationsStack implementations

• stacks in Javastacks in Java

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

What is a Stack?What is a Stack?

Linear pile of objects of one typeLinear 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 OutLIFO”: Last In = First Out

Real life stacksReal life stacks• stack of books/paperstack of books/paper• stack of plates/bowls/beer cupsstack of plates/bowls/beer cups

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

Stack OperationsStack Operations

Stacks require at least these operations:Stacks require at least these operations:• insert at top (insert at top (pushpush)) .push(item).push(item)• delete from top (delete from top (pop, pullpop, pull)) .pop().pop()

Typically have some othersTypically have some others• check if emptycheck if empty .isEmpty().isEmpty()• inspect top element (inspect top element (peek, toppeek, top)) .peek().peek()• empty it outempty it out .clear().clear()• get number of elementsget number of elements .size().size()

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

A StackA Stack

Generally arranged up & downGenerally arranged up & down• top at the toptop at the top

Old items are Old items are poppedpopped off the stack off the stack• myStack.pop()myStack.pop()

New items are New items are pushed pushed onto the stackonto the stack• myStack.push(14)myStack.push(14)

3524811257

17128

Top

Stack

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

A StackA Stack

Generally arranged up & downGenerally arranged up & down• top at the toptop at the top

Old items are Old items are poppedpopped off the stack off the stack• myStack.pop()myStack.pop()

New items are New items are pushed pushed onto the stackonto the stack• myStack.push(14)myStack.push(14)

24811257

17128

Top

Stack

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

A StackA Stack

Generally arranged up & downGenerally arranged up & down• top at the toptop at the top

Old items are Old items are poppedpopped off the stack off the stack• myStack.pop()myStack.pop()

New items are New items are pushed pushed onto the stackonto the stack• myStack.push(14)myStack.push(14)

1424811257

17128

Top

Stack

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

ExerciseExercise

Draw the Draw the stacksstacks that result from the that result from the following operations. Start with empty each following operations. Start with empty each time. Also, make a list of the items popped.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

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

Return ValuesReturn Values

Push naturally voidPush naturally void• put this thing on the stack; nothing to returnput this thing on the stack; nothing to return

Peek naturally value-returningPeek naturally value-returning• return value that is on top of stackreturn value that is on top of stack

Empty naturally boolean (empty or not?)Empty naturally boolean (empty or not?) Clear naturally voidClear naturally void Size naturally value-returningSize naturally value-returning

• number of items in the stacknumber of items in the stack

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

Return ValuesReturn Values

Pop can be either void or value-returningPop can be either void or value-returning• eithereither: take something off stack and discard it: take something off stack and discard it

» C++’s STL stack is like thisC++’s STL stack is like this

• oror: take something off stack and return it: take something off stack and return it» Java’s java.util.Stack like thisJava’s java.util.Stack like this

Pop must return value if no peek operationPop must return value if no peek operation• otherwise no way to get values otherwise no way to get values outout of the stack! of the stack!• we (text authors and I) prefer value-returningwe (text authors and I) prefer value-returning

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

Exceptional CircumstancesExceptional Circumstances

What could go wrong?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?)

Options to deal are same as with bagsOptions 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?)

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

Design DecisionsDesign Decisions

Push is naturally voidPush 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?

Peek is naturally value-returningPeek 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?

Pop can be either!Pop can be either!• boolean/null/exception all valid options!boolean/null/exception all valid options!

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

Exceptions: Checked or Not?Exceptions: Checked or Not?

Client can easily check if stack is emptyClient can easily check if stack is empty• there’s a method for thatthere’s a method for that

Client can thus write code that will never Client can thus write code that will never try to pop/peek on empty stacktry to pop/peek on empty stack

Client should not be Client should not be mademade to deal with to deal with exceptionsexceptions

Use unchecked exceptionsUse unchecked exceptions

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

Unchecked ExcUnchecked Excnns & Interfacess & Interfaces

Unchecked exceptions don’t need to be Unchecked exceptions don’t need to be mentioned in the interfacementioned in the interface

If they are mentioned, they may be ignored!If they are mentioned, they may be ignored!• implementing classes don’t need to throw themimplementing classes don’t need to throw them

» NOTE: checkedNOTE: checked exceptions exceptions cannotcannot be ignored be ignored

Interface should specify them anywayInterface 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

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

More Design DecisionsMore Design Decisions

Provide multiple versions?Provide multiple versions?• methods must have different namesmethods must have different names

» can’t have different parameters!can’t have different parameters!» pair names in some waypair names in some way

• two versions return null?two versions return null?• two versions throw exceptions?two versions throw exceptions?

How many different versions?How many different versions?• don’t want things to be too complexdon’t want things to be too complex

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

My DecisionsMy Decisions

Push not expected to failPush not expected to fail• false return value might be missed…false return value might be missed…• ……so throw an IllegalStateExceptionso throw an IllegalStateException

Two versions of pop methodTwo versions of pop method• pop throws a NoSuchElementExceptionpop throws a NoSuchElementException• pull returns null when stack is emptypull returns null when stack is empty

Two versions of peek methodTwo 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

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

My Stack InterfaceMy Stack Interface

public interface MyStackInterface<T> {public interface MyStackInterface<T> { public void push(T newEntry);public void push(T newEntry);

// throws IllegalStateException// throws IllegalStateException public T pop(); public T pop(); // throws // throws

NoSuchElementExceptionNoSuchElementException public T top(); public T top(); // throws // throws

NoSuchElementExceptionNoSuchElementException public T pull();public T pull(); // may return null// may return null public T peek();public T peek(); // may return null // may return null public boolean isEmpty();public boolean isEmpty();}}

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

Other Stack Interfaces/ClassesOther Stack Interfaces/Classes

StackInterface (from Text)StackInterface (from Text)

void push(T newEntry); void push(T newEntry); // nothing!// nothing!

T pop();T pop();

// throws EmptyStackExc// throws EmptyStackExcnn..

T peek();T peek();

// throws EmptyStackExc// throws EmptyStackExcnn..

java.util.Deque (*)java.util.Deque (*)

void push(T newEntry);void push(T newEntry);

// throws IllegalStateExc// throws IllegalStateExcnn..

// throws ClassCastExc// throws ClassCastExcnn..

// throws NullPointerExc// throws NullPointerExcnn..

// throws IllegalArgumentExc// throws IllegalArgumentExcnn..

T pop();T pop();

// throws NoSuchElementExc// throws NoSuchElementExcnn..

T peek();T peek();

// may return null// may return null

(class) java.util.Stack(class) java.util.Stack

T push(T newEntry); T push(T newEntry); // nothing// nothing

T pop(); T pop();

// throws EmptyStackExc// throws EmptyStackExcnn..

T peek();T peek();

// throws EmptyStackExc// throws EmptyStackExcnn..

(*) Deque is preferred to Stack!

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

Using StacksUsing Stacks

Balancing bracketsBalancing brackets Pre/postfix expressionsPre/postfix expressions Conversion to pre/postfix from infix (“normal”)Conversion to pre/postfix from infix (“normal”) Procedure Activation RecordsProcedure Activation Records Towers of HanoiTowers of Hanoi Railway shuntingRailway shunting Circuit designCircuit design Equivalence classesEquivalence classes Maze tracingMaze tracing

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

Balancing BracketsBalancing Brackets

Want to know if a string has the right Want to know if a string has the right number of closing brackets/parentheses/number of closing brackets/parentheses/etcetc..

Each closing item must match opening itemEach closing item must match opening item• ] for [, ) for (, ] for [, ) for (, etcetc..

Nesting may be involvedNesting 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})])])”

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

MethodMethod

Scan the string one character at a timeScan 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 when you see a closing bracket, pop a bracket

off the top & make sure it matchesoff the top & make sure it matches Return false if: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

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

CodeCode

for i for i 1 .. Length(string) 1 .. Length(string)if isOpenBracket(string[i])if isOpenBracket(string[i])

stack.push(string[i]);stack.push(string[i]);else if isCloseBracket(string[i])else if isCloseBracket(string[i])

if stack.isEmpty()if stack.isEmpty()return false;return false;

if ~match(stack.top(), string[i])if ~match(stack.top(), string[i])return false;return false;

stack.pop();stack.pop();return stack.isEmpty();return stack.isEmpty();

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

Trace ExecutionTrace Execution

““{a(1, 2), b([c, d]), {e, f, [(g), ((h))]}}”{a(1, 2), b([c, d]), {e, f, [(g), ((h))]}}”

{({ {

({

[({

({ {

{{

[{{

([{{

[{{

([{{

(([{{

([{{

[{{

{{ {

{ ( ) ( [ ] ) { [ ( ) ( ( ) ) ] } }

{{aa((1, 21, 2)), b, b([([c, dc, d])]),, { {e, f,e, f, [( [(gg)),, (( ((hh))]}}))]}}

Stack is empty: return true

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

Trace ExecutionTrace Execution

““(1, [2, 3, ([4, (5, 6), {7,8})])])”(1, [2, 3, ([4, (5, 6), {7,8})])])”

([(

([(

[([(

([([(

[([(

{[([(

[([(

( [ ( [ ( ) { } )

((1, 1, [[2, 3, 2, 3, ([([4,4, ( (5, 65, 6), {), {7,87,8})])])})])])

Mismatch: return false

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

ExerciseExercise

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

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

Postfix CalculatorPostfix Calculator

AKA Reverse Polish notationAKA Reverse Polish notation• used on HP calculatorsused on HP calculators

No need for parenthesesNo 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 * + *

Number, enter, number, operationNumber, enter, number, operation• 5 (enter) 17 (times) [85 appears]5 (enter) 17 (times) [85 appears]

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

MethodMethod

Numbers get pushedNumbers get pushed Operators:Operators:

• pop top two elementspop top two elements• do math according to operationdo math according to operation• push resultpush result

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

Trace ExecutionTrace Execution

3 5 + 8 17 6 * + *3 5 + 8 17 6 * + *

353 8

88

1788

61788

10288

1108

3 5 + 8 17 6 * + *

880

(3 + 5)*(8 + 17*6) = 8*(8 + 102) = 8*110 = 880(3 + 5)*(8 + 17*6) = 8*(8 + 102) = 8*110 = 880

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

ExerciseExercise

Evaluate the following post-fix expressionEvaluate the following post-fix expression

1 2 3 4 5 + * + * 10 /1 2 3 4 5 + * + * 10 /• show your stackshow your stack• show the equivalent infix expressionshow the equivalent infix expression

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

Conversion to PostfixConversion to Postfix

Write down operators & operations the way Write down operators & operations the way they need to be donethey need to be done• used to compile expressionsused to compile expressions

(3 + 5)*(8 + 17*6)(3 + 5)*(8 + 17*6)• 3+5 first 3+5 first 3, 5, +3, 5, +• 17*6 next 17*6 next 17, 6, *17, 6, *• 8 + (17*6) 8 + (17*6) 8,8, 17, 6, *, 17, 6, *, ++• multiply above multiply above 3, 5, +, 8, 17, 6, *, +, 3, 5, +, 8, 17, 6, *, +, **

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

Things to NoteThings to Note

(3 + 5)*(8 + 17*6) (3 + 5)*(8 + 17*6) 3 5 + 8 17 6 * + * 3 5 + 8 17 6 * + *• order of operations order of operations 17*6 instead of 8 + 17 17*6 instead of 8 + 17• parentheses parentheses 3+5 instead of 5*8 3+5 instead of 5*8• numbers written down in same ordernumbers written down in same order

Need to keep operations pendingNeed to keep operations pending• next operation may need to be done before itnext operation may need to be done before it• closing parenthesis closing parenthesis complete all ops since ( complete all ops since (

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

Trace of ConversionTrace of Conversion

(3 + 5) * (8 + 17 * 6 – 2)(3 + 5) * (8 + 17 * 6 – 2)

(+(

(*

+(*

*+(* *

( 3 + 5 )

(

+

( 8* 17 * 6 – ) \0

3 5

*

+

–(*

2

8 17 6

+(*

*

(*

+ 2

(*

– *

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

ExerciseExercise

Write Write pseudo-codepseudo-code for the infix to postfix for the infix to postfix conversionconversion• what functions would be useful?what functions would be useful?• so so useuse them! 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)

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

Stack ImplementationsStack Implementations

Can use arrays or linked structuresCan use arrays or linked structures Top is the important locationTop 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 both very much very much like a Baglike a Bag

» but we only never need to remove the latest objectbut we only never need to remove the latest object» just like how we did remove() at firstjust like how we did remove() at first

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

Stacks in JavaStacks in Java

Use Deque instead of StackUse 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.Deque;import java.util.ArrayDeque;import java.util.ArrayDeque; Deque<String> stack = new ArrayDeque<String>();Deque<String> stack = new ArrayDeque<String>();

Deques have more operations than stacksDeques 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

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

QuestionsQuestions