Outline and Reading The Stack ADT (§2.1.1) Stacks Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Stacks 2 Abstract Data Types (ADTs) The Stack ADT An abstract data The Stack ADT stores Example: ADT modeling a Auxiliary stack arbitrary objects type (ADT) is an operations: simple stock trading system Insertions and deletions abstraction of a � object top(): returns the � The data stored are buy/sell follow the last-in first-out data structure last inserted element orders scheme without removing it An ADT specifies: � The operations supported are Think of a spring-loaded � integer size(): returns the � Data stored number of elements plate dispenser � order buy(stock, shares, price) stored � Operations on the Main stack operations: � order sell(stock, shares, price) data � boolean isEmpty(): � void cancel(order) � push(object): inserts an indicates whether no � Error conditions element � Error conditions: elements are stored associated with � object pop(): removes and � Buy/sell a nonexistent stock returns the last inserted operations � Cancel a nonexistent order element Stacks 3 Stacks 4 Exceptions Applications of Stacks Attempting the In the Stack ADT, Direct applications execution of an operations pop and � Page-visited history in a Web browser operation of ADT may top cannot be � Undo sequence in a text editor sometimes cause an performed if the � Chain of method calls in the Java Virtual error condition, called stack is empty Machine an exception Attempting the Indirect applications Exceptions are said to execution of pop or � Auxiliary data structure for algorithms be “thrown” by an top on an empty operation that cannot stack throws an � Component of other data structures be executed EmptyStackException Stacks 5 Stacks 6 1
Method Stack in the JVM Array-based Stack main() { The Java Virtual Machine (JVM) Algorithm size () A simple way of int i = 5; keeps track of the chain of implementing the return t + 1 bar foo(i); active methods with a stack PC = 1 Stack ADT uses an } m = 6 When a method is called, the array Algorithm pop () JVM pushes on the stack a We add elements foo(int j) { if isEmpty () then frame containing foo from left to right int k; throw EmptyStackException PC = 3 � Local variables and return value A variable keeps k = j+1; else j = 5 � Program counter, keeping track of track of the index of t ← t − 1 bar(k); k = 6 the statement being executed the top element return S [ t + 1] } When a method ends, its frame main is popped from the stack and bar(int m) { PC = 2 … control is passed to the method S … i = 5 on top of the stack 0 1 2 t } Stacks 7 Stacks 8 Array-based Stack (cont.) Performance and Limitations The array storing the Performance stack elements may Algorithm push ( o ) � Let n be the number of elements in the stack become full if t = S.length − 1 then A push operation will � The space used is O ( n ) throw FullStackException then throw a � Each operation runs in time O (1) else FullStackException Limitations t ← t + 1 � Limitation of the array- S [ t ] ← o based implementation � The maximum size of the stack must be defined a � Not intrinsic to the priori and cannot be changed Stack ADT � Trying to push a new element into a full stack causes an implementation-specific exception … S 0 1 2 t Stacks 9 Stacks 10 Computing Spans Quadratic Algorithm 7 We show how to use a stack Algorithm spans1 ( X, n ) 6 as an auxiliary data structure Input array X of n integers 5 in an algorithm Output array S of spans of X # 4 Given an an array X , the span S ← new array of n integers n 3 S [ i ] of X [ i ] is the maximum for i ← 0 to n − 1 do n number of consecutive 2 s ← 1 n elements X [ j ] immediately 1 while s ≤ i ∧ X [ i − s ] ≤ X [ i ] 1 + 2 + … + ( n − 1) preceding X [ i ] and such that 0 s ← s + 1 1 + 2 + … + ( n − 1) X [ j ] ≤ X [ i ] S [ i ] ← s n 0 1 2 3 4 Spans have applications to return S 1 financial analysis X 6 3 4 5 2 � E.g., stock at 52-week high S 1 1 2 3 1 Algorithm spans1 runs in O ( n 2 ) time Stacks 11 Stacks 12 2
Computing Spans with a Stack Linear Algorithm Each index of the We keep in a stack the # Algorithm spans2 ( X, n ) 7 array S ← new array of n integers indices of the elements n 6 A ← new empty stack visible when “looking � Is pushed into the 1 stack exactly one 5 for i ← 0 to n − 1 do n back” � Is popped from while ( ¬ A . isEmpty () ∧ 4 We scan the array from the stack at most X [ A . top ()] ≤ X [ i ]) do n 3 once left to right A.pop () n 2 The statements in � Let i be the current index if A . isEmpty () then n the while-loop are 1 � We pop indices from the S [ i ] ← i + 1 n executed at most stack until we find index j 0 else n times such that X [ i ] < X [ j ] S [ i ] ← i − A . top () n 0 1 2 3 4 5 6 7 Algorithm spans2 � We set S [ i ] ← i − j A . push ( i ) n runs in O ( n ) time � We push x onto the stack return S 1 Stacks 13 Stacks 14 Growable Array-based Stack Comparison of the Strategies In a push operation, when Algorithm push ( o ) We compare the incremental strategy and the array is full, instead of if t = S.length − 1 then the doubling strategy by analyzing the total throwing an exception, we A ← new array of time T ( n ) needed to perform a series of n can replace the array with size … a larger one push operations for i ← 0 to t do How large should the new A [ i ] ← S [ i ] We assume that we start with an empty array be? S ← A stack represented by an array of size 1 t ← t + 1 � incremental strategy: We call amortized time of a push operation S [ t ] ← o increase the size by a the average time taken by a push over the constant c series of operations, i.e., T ( n )/ n � doubling strategy: double the size Stacks 15 Stacks 16 Incremental Strategy Analysis Doubling Strategy Analysis We replace the array k = log 2 n We replace the array k = n / c times times The total time T ( n ) of a series of n push geometric series The total time T ( n ) of a series operations is proportional to of n push operations is 2 n + c + 2 c + 3 c + 4 c + … + kc = proportional to 4 n + 1 + 2 + 4 + 8 + …+ 2 k = n + c (1 + 2 + 3 + … + k ) = 1 1 n + 2 k + 1 − 1 = 2 n − 1 n + ck ( k + 1)/2 Since c is a constant, T ( n ) is O ( n + k 2 ) , i.e., 8 T ( n ) is O ( n ) O ( n 2 ) The amortized time of a push The amortized time of a push operation is O ( n ) operation is O (1) Stacks 17 Stacks 18 3
Stack Interface in Java Array-based Stack in Java public interface Stack { Java interface public class ArrayStack public Object pop() implements Stack { corresponding to public int size(); throws EmptyStackException { our Stack ADT if isEmpty() // holds the stack elements public boolean isEmpty(); throw new EmptyStackException private Object S[ ]; Requires the (“Empty stack: cannot pop”); public Object top() definition of class // index to top element Object temp = S[top]; throws EmptyStackException; EmptyStackException private int top = -1; // facilitates garbage collection public void push(Object o); S[top] = null; Different from the // constructor top = top – 1; built-in Java class public ArrayStack(int capacity) { public Object pop() return temp; S = new Object[capacity]); java.util.Stack throws EmptyStackException; } } } Stacks 19 Stacks 20 4
Recommend
More recommend