Stacks
O tline Outline The Stack ADT Applications of Stacks Applications of Stacks Array-based implementation Growable array based stack Growable array-based stack Stacks 2
Abst act Data T pes (ADTs) Abstract Data Types (ADTs) An abstract data An abstract data Example: ADT modeling a Example: ADT modeling a type (ADT) is an simple stock trading system abstraction of a � The data stored are buy/sell � The data stored are buy/sell d t data structure t t orders An ADT specifies: � The operations supported are � Data stored Data stored � order buy(stock, shares, price) � Operations on the � order sell(stock, shares, price) data � void cancel(order) ( ) � Error conditions � Error conditions: associated with � Buy/sell a nonexistent stock operations p � Cancel a nonexistent order C l i t t d Stacks 3
The Stack ADT The Stack ADT The Stack ADT stores The Stack ADT stores Auxiliary stack Auxiliary stack arbitrary objects operations: � top(): returns a reference Insertions and deletions to the last inserted to the last inserted follow the last-in first-out element without removing scheme it Think of a spring-loaded Think of a spring-loaded � size(): returns the number size(): returns the number plate dispenser of elements stored � isEmpty(): returns a Main stack operations: Boolean value indicating Boolean value indicating � push(object o): inserts whether no elements are element o stored � pop(): removes and returns p p() the last inserted element Stacks 4
Exceptions E ceptions Attempting the Attempting the In the Stack ADT, In the Stack ADT execution of an operations pop and operation of ADT may p y top cannot be p sometimes cause an performed if the error condition, called stack is empty an exception Attempting the Exceptions are said to execution of pop or b be “thrown” by an “ h ” b top on an empty operation that cannot stack throws an be executed be executed EmptyStackException EmptyStackException Stacks 5
Applications of Stacks Applications of Stacks Direct applications � Page-visited history in a Web browser � Undo sequence in a text editor � Saving local variables when one function calls another and this one calls another and so on another, and this one calls another, and so on. Indirect applications � Auxiliary data structure for algorithms � Auxiliary data structure for algorithms � Component of other data structures Stacks 6
C+ + Run-time Stack C+ + R n time Stack main() { The C+ + run-time system The C+ + run time system int i = 5; keeps track of the chain of bar foo(i); active functions with a stack PC = 1 } } m = 6 m = 6 When a function is called the When a function is called, the run-time system pushes on the foo(int j) { stack a frame containing foo int k; ; PC = 3 PC = 3 � Local variables and return value Local variables and return value k = j+1; j = 5 � Program counter, keeping track of bar(k); k = 6 the statement being executed } } When a function returns, its When a function returns its main frame is popped from the stack bar(int m) { PC = 2 and control is passed to the … … i = 5 i 5 method on top of the stack method on top of the stack } Stacks 7
A a Array-based Stack based Stack Algorithm size () Algorithm size () A simple way of A simple way of return t + 1 implementing the Stack ADT uses an array array Algorithm pop () Al ith () We add elements if isEmpty () then from left to right throw EmptyStackException A variable keeps else t ← t − 1 track of the index of the top element p return S [ t + 1] return S [ t + 1] … S 0 1 2 t Stacks 8
A a Array-based Stack (cont.) based Stack (cont ) The array storing the The array storing the stack elements may Algorithm push ( o ) become full if t = S.length − 1 then A push operation will A push operation will throw FullStackException then throw a else FullStackException t ← t + 1 t ← t + 1 � Limitation of the array- Limitation of the array S [ t ] ← o based implementation � Not intrinsic to the Stack ADT Stack ADT … S S 0 1 2 t Stacks 9
Pe fo mance and Limitations Performance and Limitations Pe fo mance Performance � Let n be the number of elements in the stack � The space used is O ( n ) � The space used is O ( n ) � Each operation runs in time O (1) Limitations Limitations � The maximum size of the stack must be defined a priori , and cannot be changed � Trying to push a new element into a full stack causes an implementation-specific exception Stacks 10
Computing Spans Comp ting Spans 7 We show how to use a stack We show how to use a stack 6 6 as an auxiliary data structure 5 in an algorithm 4 Given an array X , the span Gi X th 3 S [ i ] of X [ i ] is the maximum 2 number of consecutive elements X [ j ] immediately l t X [ j ] i di t l 1 preceding X [ i ] and such that 0 X [ j ] ≤ X [ i ] 0 0 1 1 2 2 3 3 4 4 Spans have applications to financial analysis X 6 3 4 5 2 � E.g., stock at 52-week high g , g S 1 1 2 3 1 Stacks 11
Q ad atic Algo ithm Quadratic Algorithm Algorithm spans1 ( X n ) Algorithm spans1 ( X, n ) Input array X of n integers Output array S of spans of X # S ← new array of n integers S f i t n for i ← 0 to n − 1 do n s ← 1 n while s ≤ i ∧ X [ i − s ] ≤ X [ i ] 1 + 2 + … + ( n − 1) s ← s + 1 1 + 2 + … + ( n − 1) S [ i ] ← s S [ i ] ← s n n return S 1 Algorithm spans1 runs in O ( n 2 ) time Stacks 12
Comp ting Spans Computing Spans with a Stack ith a Stack We keep in a stack the We keep in a stack the 7 indices of the elements 6 visible when “looking 5 5 b back” k” 4 We scan the array from 3 left to right left to right 2 � Let i be the current index 1 � We pop indices from the stack until we find index j stack until we find index j 0 0 such that X [ i ] < X [ j ] 0 1 2 3 4 5 6 7 � We set S [ i ] ← i − j � We push i onto the stack We push i onto the stack Stacks 13
Linea Algo ithm Linear Algorithm Algorithm spans2 ( X, n ) # Each index of the Each index of the S ← new array of n integers n array A ← new empty stack 1 � Is pushed into the for i ← 0 to n − 1 do n stack exactly one stack exactly one while ( ¬ A . isEmpty () ∧ � Is popped from X [ top ()] ≤ X [ i ] ) do n the stack at most j ← A.pop () once n The statements in if A . isEmpty () then n S [ i ] ← i + 1 the while-loop are n executed at most else j ← top () n times n S [ i ] ← i − j n Algorithm spans2 A . push ( i ) p ( ) n runs in O ( n ) time runs in O ( n ) time return S 1 Stacks 14
G o able A a Growable Array-based Stack based Stack In a push operation when In a push operation, when Algorithm push ( o ) ( ) the array is full, instead of if t = S.length − 1 then throwing an exception, we A ← new array of y can replace the array with l th ith size … a larger one for i ← 0 to t do A [ i ] ← S [ i ] A [ i ] ← S [ i ] How large should the new How large should the new S ← A array be? t ← t + 1 � incremental strategy: gy S [ t ] ← o S [ ] increase the size by a constant c � doubling strategy: double � doubling strategy: double the size Stacks 15
Compa ison of the St ategies Comparison of the Strategies We compare the incremental strategy and the doubling strategy by analyzing the total ti time T ( n ) needed to perform a series of n T ( ) d d t f i f push operations We assume that we start with an empty We assume that we start with an empty stack represented by an array of size 1 We call amortized time of a push operation We call amortized time of a push operation the average time taken by a push over the series of operations, i.e., T ( n )/ n series of operations, i.e., T ( n )/ n Stacks 16
Inc emental St ateg Incremental Strategy Analysis Anal sis W We replace the array k = n / c times l h / i The total time T ( n ) of a series of n push operations is proportional to operations is proportional to n + c + 2 c + 3 c + 4 c + … + kc = n + c (1 + 2 + 3 + … + k ) = n + ck ( k + 1)/2 Since c is a constant, T ( n ) is O ( n + k 2 ) , i.e., O ( n 2 ) O ( n 2 ) The amortized time of a push operation is � O ( n ) ( ) Stacks 17
Do bling St ateg Doubling Strategy Analysis Anal sis We replace the array k = log 2 n 2 times The total time T ( n ) of a series geometric series of n push operations is of push operations is 2 proportional to 4 + 2 k n + 1 + 2 + 4 + 8 + n + 1 + 2 + 4 + 8 + …+ 2 1 1 1 1 = n + 2 k + 1 − 1 = 2 n − 1 2 n 1 8 T ( n ) is O ( n ) The amortized time of a push p operation is � O (1) Stacks 18
Stack Inte face in C+ + Stack Interface in C+ + template <typename Object> template typename Object I t Interface f class Stack { corresponding to public: our Stack ADT our Stack ADT int size(); int size(); bool isEmpty(); Requires the Object& top() definition of class definition of class throw(EmptyStackException); EmptyStackException void push(Object o); Most similar STL Most similar STL Object pop() Object pop() throw(EmptyStackException); construct is vector }; Stacks 19
Recommend
More recommend