cc7cb39035369010d6ffa8972cc34f92.ppt
- Количество слайдов: 28
Stacks 1
Stack q What is a stack? n n q An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO) list. Examples Stacks 2
Stack Representation q Given a stack S = (a 0, …, an-1), a 0 is the bottom element, an-1 is the top element, and ai is on top of element ai-1, 0 < i < n. a 3 a 2 a 1 a 0 Push (Add) Pop (Delete)
Abstract Data Type (ADT) q ADT (abstract data type) is an abstraction of a data structure which specifies: n n n Data stored Operations on the data Error conditions associated with operations q Example: ADT modeling a simple stock trading system n n The data stored are buy/sell orders The operations supported are w order buy(stock, shares, price) w order sell(stock, shares, price) w void cancel(order) n Error conditions: w Buy/sell a nonexistent stock w Cancel a nonexistent order Stacks 4
ADT of Stacks q Data n q q Arbitrary objects Operations n n n Exceptions (Error conditions) n push(object): inserts an element pop(): removes the last inserted element object top(): returns the last inserted element without removing it integer size(): returns the number of elements stored boolean empty(): indicates if no elements are stored Stacks n pop() and top() cannot be performed if the stack is empty. push(object) cannot be performed if the stack is full. 5
Stack Interface in C++ q q q template
Applications of Stacks No in textbook q q q Page-visited history in a web browser Undo sequence in a text editor Chain of method calls in the C++ runtime system q q q Infix to postfix No in textbook conversion Postfix expression evaluation Parenthesis matching HTML tag matching Maze solution finding No in textbook Stacks 7
C++ Run-Time Stack q q The C++ run-time system keeps track of the chain of active functions with a stack When a function is called, the system pushes on the stack a frame containing main() { int i = 5; foo(i); } foo(int j) { int k; n Local variables and return value n Program counter, keeping track of k = j+1; the statement being executed bar(k); When the function ends, its } frame is popped from the stack bar(int m) and control is passed to the { function on top of the stack … Allows for recursion } Stacks Program counter bar PC = 1 m=6 foo PC = 3 j=5 k=6 main PC = 2 i=5 8
Array-based Stack q q q A simple way of implementing the Stack ADT uses an array We add elements from left to right A variable keeps track of the index of the top element Algorithm size() return t + 1 Algorithm pop() if empty() then throw Stack. Empty else t t 1 return S[t + 1] … S 0 1 2 t Stacks 9
Array-based Stack (cont. ) q q The array storing the stack elements may Algorithm push(obj) become full if t = S. size() 1 then A push operation will throw Stack. Full then throw a Stack. Full else exception t t+1 S[t] obj … S 0 1 2 t Stacks 10
Performance and Limitations q Performance n n n q Let n be the number of elements in the stack The space used is O(n) Each operation runs in time O(1) Limitations n n 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 11
Array-based Stack in C++ template
Example use in C++ Array. Stack
Parentheses Matching q Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[” n n n correct: ( )(( )){([( )])} correct: (( )){([( )])}) incorrect: (( ))){([( )])} incorrect: ({[ ])} incorrect: (([]) Stacks 14
Parentheses Matching Algorithm Paren. Match(X, n): Input: An array X of n tokens, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number Output: true if and only if all the grouping symbols in X match Let S be an empty stack for i=0 to n-1 do if X[i] is an opening grouping symbol then S. push(X[i]) else if X[i] is a closing grouping symbol then if S. empty() then return false {nothing to match with} if S. pop() does not match the type of X[i] then return false {wrong type} if S. empty() then return true {every symbol matched} else return false {some symbols were never matched} © 2010 Goodrich, Tamassia Stacks 15
Expression Evaluation q Expressions are converted into postfix notation for evaluation n n Infix Postfix A/B–C+D*E–A*C AB/C-DE*+AC*- Operation Postfix T 1 = A / B T 1 C-DE*+AC*- T 2 = T 1 - C T 2 DE*+AC*- T 3 = D * E T 2 T 3+AC*- T 4 = T 2 + T 3 T 4 AC*- T 5 = A * C T 4 T 5 - T 6 = T 4 - T 5 T 6 Stacks 16
Postfix Notation q Advantages of postfix notation n n q Quiz! No need to use parentheses No need to consider precedence of operators Two questions n n How to change infix notation into postfix notation? How to evaluate an expression in postfix notation? Stacks 17
Infix to Postfix Conversion by Hand Three-pass algorithm: (1) Fully parenthesize expression n a/b-c+d*e-a*c ((((a / b) - c) + (d * e)) - a * c)) (2) All operators replace their corresponding right parentheses. ((((a / b) - c) + (d * e)) – (a * c))) (3) Delete all parentheses. ab/c-de*+ac*-
Rules of Conversion q Two rules n n Operators are taken out of the stack as long as their precedence is higher than or equal to the precedence of the incoming operator. The left parenthesis is placed in the stack whenever it is found in the expression, but it is unstacked only when its matching right parenthesis is found. Stacks 19
Example: Infix to Postfix The order of operands in infix and postfix are the same. a+b*c abc*+
Example: Infix to Postfix a*(b+c)/d abc+*d/ Quiz!
More Examples Quiz! Infix Postfix 2+3*4 a*b+5 (1+2)*7 a*b/c (a/(b-c+d))*(e-a)*c a/b-c+d*e-a*c 234*+ ab*5+ 12+7* ab*c/ abc-d+/ea-*c* ab/c-de*+ac*- Stacks 22
Walk-through Examples q a/b-c+d*e-a*c ab/c-de*+ac*- q Quiz! (a/(b-c+d))*(e-a)*c abc-d+/ea-*c* 23
More Examples q (a+b)*(c-d)/(e+f) ab+cd-*ef+/ Quiz! q (a+b)*(c-d)/((ef)*(g+h)) ab+cd -*ef-gh+*/ 24
Evaluating postfix expressions O(n) n Evaluation process - Make a single left-to-right scan of the expression. - Place the operands on a stack until an operator is found. - Remove, from the stack, the correct numbers of operands for the operator, perform the operation, and place the result back on the stack.
Example of Evaluating postfix expressions Example: 6 2 / 3 – 4 2 * +
Walk-through Examples n a/b-c+d*e-a*c ab/c-de*+ac*- n (a/(b-c+d))*(e-a)*c abc-d+/ea-*c* 27
Animation n n Infix to postfix conversion Postfix evaluation


