Stacks Goodrich, Tamassia

Similar documents
Stacks Goodrich, Tamassia Stacks

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.

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.

Data Structures Lecture 5

ADT Stack. Inserting and deleting elements occurs at the top of Stack S. top. bottom. Stack S

COMP9024: Data Structures and Algorithms

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

CSE Data Structures and Algorithms... In Java! Stacks. CSE2100 DS & Algorithms 1

CS212:Data Structure

Stacks Goodrich, Tamassia, Goldwasser Stacks

Foundations of Data Structures

Stacks. Lecture6: Stacks. Stack Operations. Stack Interface in Java

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

The Stack ADT. Stacks. The Stack ADT. The Stack ADT. Set of objects in which the location an item is inserted and deleted is prespecified.

Abstract Data Types (ADTs) Stacks. The Stack ADT ( 4.2) Stack Interface in Java

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

Lecture 3 Linear Data Structures

DataStruct 5. Stacks, Queues, and Deques

Lecture 3 Linear Data Structures

This lecture. Abstract Data Types (ADTs) The Stack ADT ( 4.2) Stacks. Stack Interface in Java. Exceptions. Abstract data types Stacks Queues

How many times is the loop executed? middle = (left+right)/2; if (value == arr[middle]) return true;

Lecture 3 Linear Data Structures

Ch02 Data Structures

Ch02 Data Structures

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

Collections Chapter 12. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CT 229 Object-Oriented Programming Continued

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

data structures and algorithms lecture 6

CPSC 211 Data Structures & Implementations (c) Texas A&M University [ 165] Postfix Expressions

Stacks Fall 2018 Margaret Reid-Miller

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

COMP 250 Winter stacks Feb. 2, 2016

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Data Structures And Algorithms

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

csci 210: Data Structures Stacks and Queues

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

IT 4043 Data Structures and Algorithms. Budditha Hettige Department of Computer Science

Data Abstraction and Specification of ADTs

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

Data structure and algorithm in Python

File Input and Output

CSC148 Week 2. Larry Zhang

Data Structures G5029

CSC 222: Computer Programming II. Spring 2005

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

Stacks. Revised based on textbook author s notes.

CMPS 390 Data Structures

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Assignment 5. Introduction

Classes Basic Overview

Project 1: Implementation of the Stack ADT and Its Application

Interfaces & Generics

Lex and Yacc. More Details

Do not turn to the next page until the start of the exam.

1. Stack Implementation Using 1D Array

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

COSC This week. List ADT. Abstract Data Type (ADT) Lis t ADT Implementations. Data Struc tures and Algorithms

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Standard ADTs. Lecture 19 CS2110 Summer 2009

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

CSC 273 Data Structures

University of Cape Town Department of Computer Science. Computer Science CSC115F

-The Hacker's Dictionary. Friedrich L. Bauer German computer scientist who proposed "stack method of expression evaluation" in 1955.

CMPSCI 187: Programming With Data Structures. Lecture #11: Implementing Stacks With Arrays David Mix Barrington 28 September 2012

3. Design by Contract

CSCD 326 Data Structures I Stacks

Data Structures and Algorithms " Arrays and Linked Lists!

ECM1406. Answer Sheet Lists

Today. Book-keeping. File I/O. Subscribe to sipb-iap-java-students. Inner classes. Debugging tools

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

Data Structures and Algorithms, Winter term 2018 Practice Assignment 3

CMSC 132: Object-Oriented Programming II. Stack and Queue

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

Computer Science 1 Ah

10/26/2017 CHAPTER 3 & 4. Stacks & Queues. The Collection Framework

Lab 11. A sample of the class is:

About this exam review

Assignment 4 Publication date: 27/12/2015 Submission date: 17/01/ :59 People in-charge: R. Mairon and Y. Twitto

4. Finding & Displaying Record of Salesman with minimum net income. 5. Finding & Displaying Record of Salesman with maximum net income.

Chapter 4 Defining Classes I

Application of Stack (Backtracking)

Midterm Exam 2 CS 455, Spring 2011

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Stacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved

CS 211 Programming Practicum Spring 2018

CS350: Data Structures Stacks

Postfix Notation is a notation in which the operator follows its operands in the expression (e.g ).

Exceptions and Design

COMP 250. Lecture 8. stack. Sept. 25, 2017

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

CS 211 Programming Practicum Spring 2017

Transcription:

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 Stacks 2

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 size(): returns the number of elements stored boolean isempty(): indicates whether no elements are stored Stacks 3

Stack Interface in Java Java interface corresponding to our Stack ADT Requires the definition of class EmptyStackException Different from the built-in Java class java.util.stack public interface Stack { public int size(); public boolean isempty(); public Object top() throws EmptyStackException; public void push(object o); public Object pop() throws EmptyStackException; Stacks 4

Exceptions Attempting the execution of an operation of ADT may sometimes cause an error condition, called an exception Exceptions are said to be thrown by an operation that cannot be executed In the Stack ADT, operations pop and top cannot be performed if the stack is empty Attempting the execution of pop or top on an empty stack throws an EmptyStackException Stacks 5

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

Method Stack in the JVM 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 a frame containing Local variables and return value Program counter, keeping track of the statement being executed When a method ends, its frame is popped from the stack and control is passed to the method on top of the stack Allows for recursion 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 Stacks 7

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 Algorithm size() return t + 1 Algorithm pop() if isempty() then throw EmptyStackException else t t 1 return S[t + 1] S 0 1 2 t Stacks 8

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

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

Array-based Stack in Java public class ArrayStack implements Stack { // holds the stack elements private Object S[ ]; // index to top element private int top = -1; // constructor public ArrayStack(int capacity) { S = new Object[capacity]); public Object pop() throws EmptyStackException { if isempty() throw new EmptyStackException ( Empty stack: cannot pop ); Object temp = S[top]; // facilitates garbage collection S[top] = null; top = top 1; return temp; Stacks 11

Parentheses Matching Each (, {, or [ must be paired with a matching ),, or [ correct: ( )(( )){([( )]) correct: ((( )(( )){([( )]) incorrect: )(( )){([( )]) incorrect: ({[ ]) incorrect: ( Stacks 12

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.isEmpty() 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 Stacks 13

HTML Tag Matching 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? Stacks 14

Tag Matching Algorithm Is similar to parentheses matching: import java.util.stringtokenizer; import datastructures.stack; import datastructures.nodestack; import java.io.*; /** Simpli.ed test of matching tags in an HTML document. */ public class HTML { /** Nested class to store simple HTML tags */ public static class Tag { String name; // The name of this tag boolean opening; // Is true i. this is an opening tag public Tag() { // Default constructor name = ""; opening = false; public Tag(String nm, boolean op) { // Preferred constructor name = nm; opening = op; /** Is this an opening tag? */ public boolean isopening() { return opening; /** Return the name of this tag */ public String getname() {return name; /** Test if every opening tag has a matching closing tag. */ public boolean ishtmlmatched(tag[ ] tag) { Stack S = new NodeStack(); // Stack for matching tags for (int i=0; (i<tag.length) && (tag[i]!= null); i++) { if (tag[i].isopening()) S.push(tag[i].getName()); // opening tag; push its name on the stack else { if (S.isEmpty()) // nothing to match return false; if (!((String) S.pop()).equals(tag[i].getName())) // wrong match return false; if (S.isEmpty()) return true; // we matched everything return false; // we have some tags that never were matched Stacks 15

Tag Matching Algorithm, cont. public final static int CAPACITY = 1000; // Tag array size upper bound /* Parse an HTML document into an array of html tags */ public Tag[ ] parsehtml(bufferedreader r) throws IOException { String line; // a line of text boolean intag = false ; // true iff we are in a tag Tag[ ] tag = new Tag[CAPACITY]; // our tag array (initially all null) int count = 0 ; // tag counter while ((line = r.readline())!= null) { // Create a string tokenizer for HTML tags (use < and > as delimiters) StringTokenizer st = new StringTokenizer(line,"<> \t",true); while (st.hasmoretokens()) { String token = (String) st.nexttoken(); if (token.equals("<")) // opening a new HTML tag intag = true; else if (token.equals(">")) // ending an HTML tag intag = false; else if (intag) { // we have a opening or closing HTML tag if ( (token.length() == 0) (token.charat(0)!= / ) ) tag[count++] = new Tag(token, true); // opening tag else // ending tag tag[count++] = new Tag(token.substring(1), false); // skip the // Note: we ignore anything not in an HTML tag return tag; // our array of tags /** Tester method */ public static void main(string[ ] args) throws IOException { BufferedReader stdr; // Standard Input Reader stdr = new BufferedReader(new InputStreamReader(System.in)); HTML tagchecker = new HTML(); if (tagchecker.ishtmlmatched(tagchecker.parsehtml(stdr))) System.out.println("The input file is a matched HTML document."); else System.out.println("The input file is not a matched HTML document."); Stacks 16

Computing Spans (not in book) We show how to use 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 7 6 5 4 3 2 1 0 X S 0 1 2 3 4 6 3 4 5 2 1 1 2 3 1 Stacks 17

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 Stacks 18

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 7 6 5 4 3 2 1 0 0 1 2 3 4 5 6 7 Stacks 19

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.isEmpty() X[A.top()] X[i] ) do n A.pop() n if A.isEmpty() then n S[i] i + 1 n else S[i] i A.top() n A.push(i) n return S 1 Stacks 20