Stacks CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008

Similar documents
CMPT 225. Stacks-part2

Stacks. Access to other items in the stack is not allowed A LIFO (Last In First Out) data structure

The Abstract Data Type Stack. Simple Applications of the ADT Stack. Implementations of the ADT Stack. Applications

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

n Data structures that reflect a temporal relationship q order of removal based on order of insertion n We will consider:

8/28/12. Outline. Part 2. Stacks. Linear, time ordered structures. What can we do with Coin dispenser? Stacks

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

What can we do with Coin dispenser?

Recursion as a Problem-Solving Technique. Chapter 5

infix expressions (review)

Lists are great, but. Stacks 2

Stack and Its Implementation

Stack Abstract Data Type

Application of Stack (Backtracking)

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

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.

LIFO : Last In First Out

STACKS. A stack is defined in terms of its behavior. The common operations associated with a stack are as follows:

12 Abstract Data Types

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

EC8393FUNDAMENTALS OF DATA STRUCTURES IN C Unit 3

First Semester - Question Bank Department of Computer Science Advanced Data Structures and Algorithms...

The Abstract Data Type Queue. Module 8. The Abstract Data Type Queue. The Abstract Data Type Queue. The Abstract Data Type Queue

CMPT 225. Lecture 9 Stack

Backtracking. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. The Eight Queens Problem. Chapter 5

Chapter 14. Graphs Pearson Addison-Wesley. All rights reserved 14 A-1

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

March 13/2003 Jayakanth Srinivasan,

STACKS AND QUEUES. Problem Solving with Computers-II

Stacks. Revised based on textbook author s notes.

CS 206 Introduction to Computer Science II

Lecture 4 Stack and Queue

Stacks Fall 2018 Margaret Reid-Miller

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

CS 206 Introduction to Computer Science II

CSE 214 Computer Science II Stack

Stacks and Queues. Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms

Problem with Scanning an Infix Expression

CS 206 Introduction to Computer Science II

6/4/12. Recursive void Methods. Chapter 11. Vertical Numbers. Vertical Numbers. Vertical Numbers. Algorithm for Vertical Numbers

Stacks and Queues. Chapter Stacks

! Instan:a:ng a Group of Product objects. ! InstanEaEng a Group of Friend objects. ! CollecEons can be separated into two categories

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

CS200: Queues. Prichard Ch. 8. CS200 - Queues 1

Lists, Stacks, and Queues. (Lists, Stacks, and Queues ) Data Structures and Programming Spring / 50

Linear Data Structure

Comp 249 Programming Methodology Chapter 11 Recursion

Lecture 12 ADTs and Stacks

Stacks, Queues (cont d)

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Chapter 11.!!!!Trees! 2011 Pearson Addison-Wesley. All rights reserved 11 A-1

Algorithms and Data Structures

Some Applications of Stack. Spring Semester 2007 Programming and Data Structure 1

Lab 7 1 Due Thu., 6 Apr. 2017

// The next 4 functions return true on success, false on failure

An Introduction to Trees

CSC 273 Data Structures

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

CSC 222: Computer Programming II. Spring 2005

Stacks and Queues as Collections

[CS302-Data Structures] Homework 2: Stacks

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

Top of the Stack. Stack ADT

Outline. Stacks. 1 Chapter 5: Stacks and Queues. favicon. CSI33 Data Structures

Why Generic Types? Structured Code Reuse. Why Generic Types? Structured Code Reuse. Type parameters (generics) 10/17/14. Type parameter. Awkward.

Postfix (and prefix) notation

Formal Languages and Automata Theory, SS Project (due Week 14)

Algorithms and Data Structures

CS 211. Project 5 Infix Expression Evaluation

Chapter 5. Decrease-and-Conquer. Copyright 2007 Pearson Addison-Wesley. All rights reserved.

Chapter 18: Stacks And Queues. Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Programming, Data Structures and Algorithms Prof. Hema A Murthy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Introduction. Problem Solving on Computer. Data Structures (collection of data and relationships) Algorithms

Basic Data Structures

Foundations of Data Structures

Recursive Definitions

Stacks. Manolis Koubarakis. Data Structures and Programming Techniques

Outline. Introduction Stack Operations Stack Implementation Implementation of Push and Pop operations Applications. ADT for stacks

ABSTRACT DATA TYPES (ADTS) COMP1927 Computing 2 16x1 Sedgewick Chapter 4

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

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

LECTURE 17 GRAPH TRAVERSALS

Trees 11/15/16. Chapter 11. Terminology. Terminology. Terminology. Terminology. Terminology

CS 171: Introduction to Computer Science II. Stacks. Li Xiong

Data Structure (CS301)

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

Largest Online Community of VU Students

MIDTERM EXAMINATION Spring 2010 CS301- Data Structures

Module 10. Recursion. Adapted from Absolute Java, Rose Williams, Binghamton University

Computer Science BS Degree - Data Structures (I2206) Abstract Data Types (ADT)

Lecture 4: Stack Applications CS2504/CS4092 Algorithms and Linear Data Structures. Parentheses and Mathematical Expressions

CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues

Backtracking. Module 6. The Eight Queens Problem. CS 147 Sam Houston State University Dr. McGuire. Backtracking. Recursion Revisited

Top of the Stack. Stack ADT

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

File Input and Output

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Abstract Data Types. Stack. January 26, 2018 Cinda Heeren / Geoffrey Tien 1

Cpt S 122 Data Structures. Course Review Midterm Exam # 1

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

Transcription:

Chapter 7 s CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008 The Abstract Data Type: Specifications of an abstract data type for a particular problem Can emerge during the design of the problem s solution Examples readandcorrect algorithm displaybackward algorithm 2006 Pearson Addison-Wesley. All rights reserved 7-1 2006 Pearson Addison-Wesley. All rights reserved 7-2 ADT stack operations Create an empty stack Determine whether a stack is empty Add a new item to the stack Remove from the stack the item that was added most recently Remove all the items from the stack Retrieve from the stack the item that was added most recently A stack Last-in, first-out (LIFO) property The last item placed on the stack will be the first item removed Analogy A stack of dishes in a cafeteria Figure 7-1 of cafeteria dishes 2006 Pearson Addison-Wesley. All rights reserved 7-3 2006 Pearson Addison-Wesley. All rights reserved 7-4 A queue First in, first out (FIFO) property The first item added is the first item to be removed Refining the Definition of the ADT Pseudocode for the ADT stack operations create() // Creates an empty stack. isempty() // Determines whether a stack is empty. push(newitem) throws Exception // Adds newitem to the top of the stack. // Throws Exception if the insertion is // not successful. 2006 Pearson Addison-Wesley. All rights reserved 7-5 2006 Pearson Addison-Wesley. All rights reserved 7-6

Refining the Definition of the ADT Pseudocode for the ADT stack operations (Continued) pop() throws Exception // Retrieves and then removes the top of the stack. // Throws Exception if the deletion is not // successful. popall() // Removes all items from the stack. Using the ADT in a Solution displaybackward and readandcorrect algorithms can be refined by using stack operations A program can use a stack independently of the stack s implementation peek() throws Exception // Retrieves the top of the stack. Throws // Exception if the retrieval is not successful 2006 Pearson Addison-Wesley. All rights reserved 7-7 2006 Pearson Addison-Wesley. All rights reserved 7-8 Axioms (Optional) Axioms are used to define an ADT formally Example Axiom to specify that the last item inserted into stack is the first item to be removed (stack.push(newitem)).pop() = stack Simple Applications of the ADT : Checking for Balanced Braces A stack can be used to verify whether a program contains balanced braces An example of balanced braces abc{defg{ijk}{l{mn}}op}qr An example of unbalanced braces abc{def}}{ghij{kl}m 2006 Pearson Addison-Wesley. All rights reserved 7-9 2006 Pearson Addison-Wesley. All rights reserved 7-10 Checking for Balanced Braces Checking for Balanced Braces Requirements for balanced braces Each time you encounter a }, it matches an already encountered { When you reach the end of the string, you have matched each { Figure 7-3 Traces of the algorithm that checks for balanced braces 2006 Pearson Addison-Wesley. All rights reserved 7-11 2006 Pearson Addison-Wesley. All rights reserved 7-12

Checking for Balanced Braces The exception Exception A Java method that implements the balanced-braces algorithm should do one of the following Take precautions to avoid an exception Provide try and catch blocks to handle a possible exception Recognizing Strings in a Language Language L L = {w$w : w is a possible empty string of characters other than $, w = reverse(w) } A stack can be used to determine whether a given string is in L Traverse the first half of the string, pushing each character onto a stack Once you reach the $, for each character in the second half of the string, pop a character off the stack Match the popped character with the current character in the string 2006 Pearson Addison-Wesley. All rights reserved 7-13 2006 Pearson Addison-Wesley. All rights reserved 7-14 Implementations of the ADT The ADT stack can be implemented using An array A linked list The ADT list Interface Provides a common specification for the three implementations Exception Used by Interface Extends java.lang.runtimeexception Implementations of the ADT Figure 7-4 Implementation of the ADT stack that use a) an array; b) a linked list; c) an ADT list 2006 Pearson Addison-Wesley. All rights reserved 7-15 2006 Pearson Addison-Wesley. All rights reserved 7-16 An Array-Based Implementation of the ADT ArrayBased class Implements Interface Instances s Private data fields An array of Objects called items The index top A Reference-Based Implementation of the ADT A reference-based implementation Required when the stack needs to grow and shrink dynamically ReferenceBased Implements Interface top is a reference to the head of a linked list of items Figure 7-5 An array-based implementation 2006 Pearson Addison-Wesley. All rights reserved 7-17 2006 Pearson Addison-Wesley. All rights reserved 7-18

A Reference-Based Implementation of the ADT Figure 7-6 A reference-based implementation An Implementation That Uses the ADT List The ADT list can be used to represent the items in a stack If the item in position 1 of a list represents the top of the stack push(newitem) operation is implemented as add(1, newitem) pop() operation is implemented as get(1) remove(1) peek() operation is implemented as get(1) 2006 Pearson Addison-Wesley. All rights reserved 7-19 2006 Pearson Addison-Wesley. All rights reserved 7-20 An Implementation That Uses the ADT List Comparing Implementations Figure 7-7 An implementation that uses the ADT list All of the three implementations are ultimately array based or reference based Fixed size versus dynamic size An array-based implementation Uses fixed-sized arrays Prevents the push operation from adding an item to the stack if the stack s size limit has been reached A reference-based implementation Does not put a limit on the size of the stack 2006 Pearson Addison-Wesley. All rights reserved 7-21 2006 Pearson Addison-Wesley. All rights reserved 7-22 Comparing Implementations An implementation that uses a linked list versus one that uses a reference-based implementation of the ADT list Linked list approach More efficient ADT list approach Reuses an already implemented class Much simpler to write Saves time The Java Collections Framework Class JCF contains an implementation of a stack class called (generic) Derived from Vector Includes methods: peek, pop, push, and search search returns the 1-based position of an object on the stack 2006 Pearson Addison-Wesley. All rights reserved 7-23 2006 Pearson Addison-Wesley. All rights reserved 7-24

Application: Algebraic Expressions When the ADT stack is used to solve a problem, the use of the ADT s operations should not depend on its implementation To evaluate an infix expressions Convert the infix expression to postfix form Evaluate the postfix expression Evaluating Postfix Expressions A postfix calculator Requires you to enter postfix expressions Example: 2, 3, 4, +, * When an operand is entered, the calculator Pushes it onto a stack When an operator is entered, the calculator Applies it to the top two operands of the stack Pops the operands from the stack Pushes the result of the operation on the stack 2006 Pearson Addison-Wesley. All rights reserved 7-25 2006 Pearson Addison-Wesley. All rights reserved 7-26 Evaluating Postfix Expressions Evaluating Postfix Expressions Figure 7-8 The action of a postfix calculator when evaluating the expression 2 * (3 + 4) 2006 Pearson Addison-Wesley. All rights reserved 7-27 To evaluate a postfix expression which is entered as a string of characters Simplifying assumptions The string is a syntactically correct postfix expression No unary operators are present No exponentiation operators are present Operands are single lowercase letters that represent integer values 2006 Pearson Addison-Wesley. All rights reserved 7-28 Converting Infix Expressions to Equivalent Postfix Expressions Converting Infix Expressions to Equivalent Postfix Expressions An infix expression can be evaluated by first being converted into an equivalent postfix expression Facts about converting from infix to postfix Operands always stay in the same order with respect to one another An operator will move only to the right with respect to the operands All parentheses are removed Figure 7-9 Figure 7-9 A trace of the algorithm that converts the infix expression a - (b + c * d)/e to postfix form 2006 Pearson Addison-Wesley. All rights reserved 7-29 2006 Pearson Addison-Wesley. All rights reserved 7-30

Application: A Search Problem Representing the Flight Data High Planes Airline Company (HPAir) Problem For each customer request, indicate whether a sequence of HPAir flights exists from the origin city to the destination city The flight map for HPAir is a graph Adjacent vertices Two vertices that are joined by an edge Directed path A sequence of directed edges 2006 Pearson Addison-Wesley. All rights reserved 7-31 Figure 7-10 Flight map for HPAir 2006 Pearson Addison-Wesley. All rights reserved 7-32 A Nonrecursive Solution that Uses a A Nonrecursive Solution that Uses a The solution performs an exhaustive search Beginning at the origin city, the solution will try every possible sequence of flights until either It finds a sequence that gets to the destination city It determines that no such sequence exists The ADT stack is useful in organizing an exhaustive search Backtracking can be used to recover from a wrong choice of a city Figure 7-11 The stack of cities as you travel a) from P; b) to R; c) to X; d) back to R; e) back to P; f) to W 2006 Pearson Addison-Wesley. All rights reserved 7-33 2006 Pearson Addison-Wesley. All rights reserved 7-34 A Nonrecursive Solution that Uses a A Recursive Solution Figure 7-13 A trace of the search algorithm, given the flight map in Figure 6-9 2006 Pearson Addison-Wesley. All rights reserved 7-35 Possible outcomes of the recursive search strategy You eventually reach the destination city and can conclude that it is possible to fly from the origin to the destination You reach a city C from which there are no departing flights You go around in circles 2006 Pearson Addison-Wesley. All rights reserved 7-36

A Recursive Solution A refined recursive search strategy searchr(origincity, destinationcity) Mark origincity as visited if (origincity is destinationcity) { Terminate -- the destination is reached } else { for (each unvisited city C adjacent to origincity) { searchr(c, destinationcity) } } The Relationship Between s and Recursion The ADT stack has a hidden presence in the concept of recursion Typically, stacks are used by compilers to implement recursive methods During execution, each recursive call generates an activation record that is pushed onto a stack s can be used to implement a nonrecursive version of a recursive algorithm 2006 Pearson Addison-Wesley. All rights reserved 7-37 2006 Pearson Addison-Wesley. All rights reserved 7-38 Summary ADT stack operations have a last-in, first-out (LIFO) behavior Algorithms that operate on algebraic expressions are an important application of stacks A stack can be used to determine whether a sequence of flights exists between two cities A strong relationship exists between recursion and stacks 2006 Pearson Addison-Wesley. All rights reserved 7-39