Stacks and Queues 1 Stacks Stack what is

  • Slides: 25
Download presentation
Stacks (and Queues) 1

Stacks (and Queues) 1

Stacks Stack: what is it? q ADT q Applications q Implementation(s) q 2

Stacks Stack: what is it? q ADT q Applications q Implementation(s) q 2

Stacks and queues 1. 2. 3. 4. 5. A stack is a very important

Stacks and queues 1. 2. 3. 4. 5. A stack is a very important data structure in computing science. A stack is a sequence of elements to which new elements are added (pushed), and from which elements are removed (popped), at the same end. Stack sometimes referred to as a last in, first out structure (LIFO). In a queue, elements are removed from the opposite end to which they are added. Queue sometimes referred to as a first in, first out structure (FIFO). 3

Stacks and queues q The difference is the remove operation. add remove 4

Stacks and queues q The difference is the remove operation. add remove 4

Last In First Out A B top A C top B A D top

Last In First Out A B top A C top B A D top C B A E top D C B A 5

The Stack ADT 1. 2. 3. The Stack ADT stores arbitrary objects Insertions and

The Stack ADT 1. 2. 3. The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in firstout scheme Think of a spring-loaded plate dispenser. (Pez? ) 7

The Stack ADT 1. Main stack operations: 1. 2. push(object): inserts an element Object

The Stack ADT 1. Main stack operations: 1. 2. push(object): inserts an element Object pop(): removes and returns the last inserted element Auxiliary stack operations: Object peek(): returns the last inserted element without removing it. (Sometimes appears as Object top()) 2. integer size(): returns the number of elements stored 3. boolean is. Empty(): indicates whether no elements are stored WHICH ONES ARE ACCESSOR OR MUTATOR METHODS? ? ? 1. 8

Stack Operations Assume a simple stack for integers. Stack s = new Stack(); s.

Stack Operations Assume a simple stack for integers. Stack s = new Stack(); s. push(12); s. push(4); s. push( s. top() + 2 ); s. pop() s. push( s. top() ); //what are contents of stack? 9

Stack usage and limitations Write an algorithm to Reverse the contents of an array.

Stack usage and limitations Write an algorithm to Reverse the contents of an array. How about using a stack? Write a method to print out contents of stack in reverse order. 10

Applications of Stacks q Direct applications n n n q Page-visited history in a

Applications of Stacks q Direct applications n n n q Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in the Java Virtual Machine Indirect applications n n Auxiliary data structure for algorithms Component of other data structures 13

Method Stack in the JVM 1. 2. The Java Virtual Machine (JVM) keeps track

Method Stack in the JVM 1. 2. The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack When a method is called, the JVM pushes on the stack 1. 2. 3. Local variables and return value Program counter, keeping track of the statement being executed When a method ends, it’s popped from the stack and control is passed to the method on top of the stack main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } bar PC = 1 m=6 foo PC = 3 j=5 k=6 main PC = 2 i=5 14

Array-based Stack 1. Allocate an array of some size (pre-defined) 1. 2. 3. Bottom

Array-based Stack 1. Allocate an array of some size (pre-defined) 1. 2. 3. Bottom stack element stored at element 0 last index in the array is the top 1. 4. Maximum N elements in stack What is index when stack is empty? Increment top when one element is pushed, decrement after pop 15

Array-based Stack Algorithm size() return top + 1 Algorithm pop() if is. Empty() then

Array-based Stack Algorithm size() return top + 1 Algorithm pop() if is. Empty() then throw Empty. Stack. Exception else top 1 return S[top + 1] … S 0 1 2 t 16

Array-based Stack (cont. ) q q The array storing the stack elements may become

Array-based Stack (cont. ) q q The array storing the stack elements may become full A push operation will then throw a Full. Stack. Exception n n Algorithm push(o) if t = S. length 1 then throw Full. Stack. Exception else t t+1 Limitation of the array. S[t] o based implementation Not intrinsic to the Stack ADT … S 0 1 2 t 17

Performance and Limitations 1. Performance 1. 2. 3. 2. Let n be the number

Performance and Limitations 1. Performance 1. 2. 3. 2. Let n be the number of elements in the stack The space used is O(n) Each operation runs in time O(1) Limitations 1. 2. 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 18

Common Stack Error Stack s = new Stack(); // put stuff in stack for(int

Common Stack Error Stack s = new Stack(); // put stuff in stack for(int i = 0; i < 7; i++) s. push( i ); // print out contents of stack // while emptying it for(int i = 0; i < s. size(); i++) System. out. println( s. pop() ); // Output? Why? 19

Corrected Version Stack s = new Stack(); // put stuff in stack for(int i

Corrected Version Stack s = new Stack(); // put stuff in stack for(int i = 0; i < 7; i++) s. push( i ); // print out contents of stack // while emptying it int limit = s. size(); for(int i = 0; i < limit; i++) System. out. println( s. pop() ); //or // while( !s. is. Empty() ) // System. out. println( s. pop() ); 20

Parentheses Matching q Each “(”, “{”, or “[” must be paired with a matching

Parentheses Matching q Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[” n n n correct: ( )(( )){([( )])} correct: ((( )){([( )])} incorrect: )(( )){([( )])} incorrect: ({[ ])} incorrect: ( 23

Parentheses Matching Algorithm Paren. Match(X, n): Input: An array X of n tokens, each

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. is. 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. is. Empty() then return true {every symbol matched} else return false {some symbols were never matched} 24

HTML Tag Matching For fully-correct HTML, each <name> should pair with a matching </name>

HTML Tag Matching For fully-correct HTML, each <name> should pair with a matching </name> <body> <center> <h 1> The Little Boat </h 1> </center> <p> The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. </p> <ol> <li> Will the salesman die? </li> <li> What color is the boat? </li> <li> And what about Naomi? </li> </ol> </body> The Little Boat The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. 1. Will the salesman die? 2. What color is the boat? 3. And what about Naomi? 25

Infix notation q q q q Consider the arithmetic expression: 3 + 4 *

Infix notation q q q q Consider the arithmetic expression: 3 + 4 * (5 - 2) - 3 - 1 Binary operators requires two operands. To evaluate the expression, we use the following rules: * and / have higher precedence than + and -, when operators have the same precedence, we apply them from left to right, brackets change the order of precedence. Hence the following example gives a different answer: 3 + 4 * 5 - 2 - (3 - 1) Consider a system of arithmetic with different rules… 26

Reverse Polish q q q With reverse Polish (postfix) notation, no precedence rules or

Reverse Polish q q q With reverse Polish (postfix) notation, no precedence rules or parentheses required! In postfix notation, we put the operator after its operands instead of between them. Hence, instead of 5 + 4, we have 5 4 +. 27

Postfix Notation q q q The first expression above, would be re-written as: 3

Postfix Notation q q q The first expression above, would be re-written as: 3 + 4 * (5 - 2) - 3 - 1 3 4 5 2 - * + 3 - 1 – while the second would be written as: 3 + 4 * 5 - 2 - (3 - 1) 3 4 5 * + 2 - 3 1 - The operands are written in the same order while the operators are now written in the order in which they are to be applied. 28

Evaluating Postfix Expressions 29

Evaluating Postfix Expressions 29

Examples q Let us first apply it to our simple example: 5 4 +

Examples q Let us first apply it to our simple example: 5 4 + Next ‘Token’: q 5 5 4 + 9 Answer is 9 With the expression: 3 4 5 2 - * + 3 - 1 - Next 2 5 4 3 3 4 3 12 3 - * + 15 3 15 12 1 12 3 - 1 - 30 11