Stacks © 2013 Goodrich, Tamassia, Goldwasser Stacks.

Slides:



Advertisements
Similar presentations
Stacks.
Advertisements

Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks. Queues. Double-Ended Queues. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
Stacks. 2 Outline and Reading The Stack ADT (§4.2.1) Applications of Stacks (§4.2.3) Array-based implementation (§4.2.2) Growable array-based stack.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Applications of Stacks Direct applications Delimiter matching Undo sequence in a text.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks, Queues, and Deques
Data Structures Lecture 5 Fang Yu Department of Management Information Systems National Chengchi University Fall 2010.
Topic 15 Implementing and Using Stacks
Stacks and QueuesCSC311: Data Structures1 Chapter 5 Stacks and Queues Objectives –Stacks and implementations –Queues and implementations –Double-ended.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5)
Topic 15 Implementing and Using Stacks
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Stacks1 CS2468 Data Structures and Data Management Lecturer: Lusheng Wang Office: B6422 Phone:
Stacks. week 2a2 Outline and Reading The Stack ADT (§4.1) Applications of Stacks Array-based implementation (§4.1.2) Growable array-based stack Think.
Stacks. 2 What Are Stacks ? PUSHPOP 0 MAX Underflow Overflow.
Stacks © 2010 Goodrich, Tamassia1Stacks. 2 Abstract Data Types (ADTs)  An abstract data type (ADT) is an abstraction of a data structure  An ADT specifies:
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Stack. Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data.
Stacks & Queues EECS: Stacks & Queues Stacks April 23, 2017
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
30 May Stacks (5.1) CSE 2011 Winter Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An.
STACKS AND QUEUES 1. Outline 2  Stacks  Queues.
Lecture6: Stacks Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
Welcome to CSCE 221 – Data Structures and Algorithms
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks A stack is a linear data structure that can be accessed only at one of its ends for storing and retrieving data LIFO (Last In First Out) structure.
Stack. ADS2 Lecture 1010 The Stack ADT (GoTa §5.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stack: Last In First Out (LIFO).–Used in procedure calls, to compute arithmetic expressions.
Stacks Presentation for use with the textbook Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Stacks 1/25/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Stacks (and Queues).
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Stacks 5/2/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,
Stacks Stacks.
CSCI 3333 Data Structures Stacks.
Stacks.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Stacks 9/12/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Stacks Chapter 4.
Algorithms and Data Structures
Arrays, Stacks, and Queues
Stack Data Structure, Reverse Polish Notation, Homework 7
Stacks and queues.
Stacks.
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks.
Chapter 5 Stacks and Queues 11/28/2018 Stacks.
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
Stacks 12/7/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H.
Copyright © Aiman Hanna All rights reserved
Recall What is a Data Structure Very Fundamental Data Structures
Stacks Abstract Data Types (ADTs) Stacks
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks and Queues DSA 2013 Stacks n Queues.
Stacks.
Stacks.
Topic 15 Implementing and Using Stacks
Introduction to Stacks
Computing Spans Given an an array X, the span S[i] of X[i] is
Introduction to Stacks
Presentation transcript:

Stacks © 2013 Goodrich, Tamassia, Goldwasser Stacks

Assignment #4: Array-based sequences R-5.2 In Code Fragment 5.1, we perform an experiment to compare the length of a Python list to its underlying memory usage. Determining the sequence of array sizes requires a manual inspection of the output of that program. Redesign the experiment so that the program outputs only those values of k at which the existing capacity is exhausted. For example, on a system consistent with the results of Code Fragment 5.2, your program should output that the sequence of array capacities are 0, 4, 8, 16, 25, . . . . R-5.4 Our DynamicArray class, as given in Code Fragment 5.3, does not support use of negative indices with __getitem__ . Update that method to better match the semantics of a Python list. R-5.6 Our implementation of insert for the DynamicArray class, as given in Code Fragment 5.5, has the following inefficiency. In the case when a resize occurs, the resize operation takes time to copy all the elements from an old array to a new array, and then the subsequent loop in the body of insert shifts many of those elements. Give an improved implementation of the insert method, so that, in the case of a resize, the elements are shifted into their final position during that operation, thereby avoiding the subsequent shifting. Array-Based Sequences

R-5.2 outputs only those values of k at which the existing capacity is exhausted

R-5.4 support use of negative indices

R-5.6 avoiding the subsequent shifting

Three applications based on stack Evaluating Arithmetic Expressions Computing Spans (not in book) © 2013 Goodrich, Tamassia, Goldwasser Stacks

Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error conditions associated with operations Example: ADT modeling a simple stock trading system The data stored are buy/sell orders The operations supported are order buy(stock, shares, price) order sell(stock, shares, price) void cancel(order) Error conditions: Buy/sell a nonexistent stock Cancel a nonexistent order © 2013 Goodrich, Tamassia, Goldwasser Stacks

The Stack ADT The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme Think of a spring-loaded plate dispenser Main stack operations: push(object): inserts an element object pop(): removes and returns the last inserted element Auxiliary stack operations: object top(): returns the last inserted element without removing it integer len(): returns the number of elements stored boolean is_empty(): indicates whether no elements are stored © 2013 Goodrich, Tamassia, Goldwasser Stacks

Example © 2013 Goodrich, Tamassia, Goldwasser Stacks

Applications of Stacks Direct applications Page-visited history in a Web browser Undo sequence in a text editor Chain of method calls in a language that supports recursion Indirect applications Auxiliary data structure for algorithms Component of other data structures © 2013 Goodrich, Tamassia, Goldwasser Stacks

Array-based Stack 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 … S 1 2 t © 2013 Goodrich, Tamassia, Goldwasser Stacks

Array-based Stack (cont.) The array storing the stack elements may become full A push operation will then need to grow the array and copy all the elements over. S 1 2 t … © 2013 Goodrich, Tamassia, Goldwasser Stacks

Performance and Limitations Let n be the number of elements in the stack The space used is O(n) Each operation runs in time O(1) (amortized in the case of a push) © 2013 Goodrich, Tamassia, Goldwasser Stacks

Array-based Stack in Python © 2013 Goodrich, Tamassia, Goldwasser Stacks

Example © 2013 Goodrich, Tamassia, Goldwasser Stacks http://www.tutorialspoint.com/python/python_pass_statement.htm The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example): © 2013 Goodrich, Tamassia, Goldwasser Stacks

Parentheses Matching Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[” correct: ( )(( )){([( )])} correct: ((( )(( )){([( )])} incorrect: )(( )){([( )])} incorrect: ({[ ])} incorrect: ( © 2013 Goodrich, Tamassia, Goldwasser Stacks

Parentheses Matching Algorithm Algorithm ParenMatch(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.isEmpty() then return true {every symbol matched} else return false {some symbols were never matched} © 2013 Goodrich, Tamassia, Goldwasser Stacks

Parentheses Matching in Python © 2013 Goodrich, Tamassia, Goldwasser Stacks

HTML Tag Matching The Little Boat For fully-correct HTML, each <name> should pair with a matching </name> <body> <center> <h1> The Little Boat </h1> </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? © 2013 Goodrich, Tamassia, Goldwasser Stacks

Tag Matching Algorithm in Python © 2013 Goodrich, Tamassia, Goldwasser Stacks

© 2013 Goodrich, Tamassia, Goldwasser Stacks

Evaluating Arithmetic Expressions Slide by Matt Stallmann included with permission. Evaluating Arithmetic Expressions 14 – 3 * 2 + 7 = (14 – (3 * 2) ) + 7 Operator precedence * has precedence over +/– Associativity operators of the same precedence group evaluated from left to right Example: (x – y) + z rather than x – (y + z) Idea: push each operator on the stack, but first pop and perform higher and equal precedence operations. © 2013 Goodrich, Tamassia, Goldwasser Stacks

Algorithm for Evaluating Expressions Slide by Matt Stallmann included with permission. Algorithm for Evaluating Expressions Two stacks: Algorithm EvalExp() opStk holds operators Input: a stream of tokens representing an arithmetic expression (with numbers) valStk holds values Use $ as special “end of input” token with lowest precedence Output: the value of the expression Algorithm doOp() while there’s another token z x  valStk.pop(); if isNumber(z) then y  valStk.pop(); valStk.push(z) op  opStk.pop(); else valStk.push( y op x ) Algorithm repeatOps( refOp ): repeatOps(z); while ( valStk.size() > 1  opStk.push(z) repeatOps($); prec(refOp) ≤ prec(opStk.top()) return valStk.top() doOp() © 2013 Goodrich, Tamassia, Goldwasser Stacks

Algorithm on an Example Expression Slide by Matt Stallmann included with permission. Algorithm on an Example Expression Operator ≤ has lower precedence than +/– 14 ≤ 4 – 3 * 2 + 7 * 3 – ≤ 14 4 – ≤ 14 4 + 2 * 3 – ≤ 14 4 + ≤ 14 -2 2 * 3 – ≤ 14 4 + 6 – ≤ 14 4 $ 7 + ≤ 14 -2 $ F $ ≤ 14 5 © 2013 Goodrich, Tamassia, Goldwasser Stacks

Postfix Expressions (1/2) Issues: 4.99+5.99+6.99*1.06 = 19.05 or 18.39 4.99*1.06+5.99+6.99*1.06 = 18.69 or 19.37 Postfix or reverse Polish notation multiply 4.99 and 1.06,saving this answer as A1. We then add 5.99 and A1, saving the result in A1. We multiply 6.99 and 1.06, saving the answer in A2, and finish by adding A1 and A2, leaving the final answer in A1. 4.99 1.06 * 5.99 + 6.99 1.06 * +

Postfix Expressions (2/2) Use a stack. When a number is seen, it is pushed onto the stack; when an operator is seen, the operator is applied to the two numbers (symbols) that are popped from the stack, and the result is pushed onto the stack. For instance, the postfix expression 6 5 2 3 + 8 ∗ +3 + ∗ The time to evaluate a postfix expression is O(N), no need to know any precedence rules

Infix to Postfix Conversion (1/2) convert an expression in standard form (otherwise known as infix) into postfix The idea of this algorithm is that when an operator is seen, it is placed on the stack. The stack represents pending operators. However, some of the operators on the stack that have high precedence are now known to be completed and should be popped, as they will no longer be pending. Thus prior to placing the operator on the stack, operators that are on the stack, and which are to be completed prior to the current operator, are popped.

Infix to Postfix Conversion (2/2) convert the infix expression a + b * c + ( d * e + f ) * g into postfix. A correct answer is a b c * + d e * f + g * +.

Computing Spans (not in book) Using a stack as an auxiliary data structure in an algorithm Given an an array X, the span S[i] of X[i] is the maximum number of consecutive elements X[j] immediately preceding X[i] and such that X[j]  X[i] Spans have applications to financial analysis E.g., stock at 52-week high X 6 3 4 5 2 1 S © 2013 Goodrich, Tamassia, Goldwasser Stacks

Quadratic Algorithm Algorithm spans1(X, n) Input array X of n integers Output array S of spans of X # S  new array of n integers 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 n return S 1 Algorithm s pans1 runs in O(n2) time © 2013 Goodrich, Tamassia, Goldwasser Stacks

http://www.studyalgorithms.com/array/finding-spans-in-an-array/ Finding spans in an array. Question: Find spans in an array. Given an array arr[], the SPAN s[i] of arr[i] is the maximum number of consecutive elements arr[j] immediately before arr[i] such that arr[j] <= arr[i]. Let us try to understand the question once again. This is a very common problem in stock markets to find the peaks. Spans have applications to financial analysis(Example:- You might have heard a saying “STOCKS AT 52 WEEK HIGH”). The span of a stocks price on certain day, i , is the maximum number of consecutive days (up-to the current day) the price of the stock has been less than or equal to its price on i.

Computing Spans with a Stack We keep in a stack the indices of the elements visible when “looking back” We scan the array from left to right Let i be the current index We pop indices from the stack until we find index j such that X[i]  X[j] We set S[i]  i - j We push x onto the stack © 2013 Goodrich, Tamassia, Goldwasser Stacks

Linear Algorithm Each index of the array Is pushed into the stack exactly one Is popped from the stack at most once The statements in the while-loop are executed at most n times Algorithm spans2 runs in O(n) time Algorithm spans2(X, n) # S  new array of n integers n A  new empty stack 1 for i  0 to n  1 do n while (A.is_empty()  X[A.top()]  X[i] ) do n A.pop() n if A.is_empty() then n S[i]  i + 1 n else S[i]  i - A.top() n A.push(i) n return S 1 © 2013 Goodrich, Tamassia, Goldwasser Stacks