Stacks. Developing an ADT. Chapter 7. Developing an ADT During the Design of a Solution. Refining the Definition of the ADT Stack

Similar documents
Data Structures and Algorithms V Otávio Braga

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

7.1 Our Current Model

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Chapter 3: Restricted Structures Page 1

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

Data Structures Using C++ 2E. Chapter 5 Linked Lists

DATA STRUCTURES USING C

Algorithms and Data Structures

Module 2 Stacks and Queues: Abstract Data Types

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Introduction to Data Structures

Stacks. Linear data structures

Introduction to Stacks

Outline. The Stack ADT Applications of Stacks Array-based implementation Growable array-based stack. Stacks 2

Data Structures and Algorithms Stacks and Queues

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

The following themes form the major topics of this chapter: The terms and concepts related to trees (Section 5.2).

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Linked Lists Linked Lists, Queues, and Stacks

DATA STRUCTURE - STACK

Data Structure [Question Bank]

Lecture 2: Data Structures Steven Skiena. skiena

Universidad Carlos III de Madrid

Sequential Data Structures

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Stacks. Data Structures and Data Types. Collections

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

10CS35: Data Structures Using C

Application of Stacks: Postfix Expressions Calculator (cont d.)

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

Analysis of a Search Algorithm

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Converting a Number from Decimal to Binary

St S a t ck a ck nd Qu Q eue 1

PES Institute of Technology-BSC QUESTION BANK

Regular Expressions and Automata using Haskell

STACKS,QUEUES, AND LINKED LISTS

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Catalan Numbers. Thomas A. Dowling, Department of Mathematics, Ohio State Uni- versity.

2. (a) Explain the strassen s matrix multiplication. (b) Write deletion algorithm, of Binary search tree. [8+8]

3 Abstract Data Types and Search

Common Data Structures

JavaScript: Control Statements I

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

Chapter 14 The Binary Search Tree

What Is Recursion? Recursion. Binary search example postponed to end of lecture

2) Write in detail the issues in the design of code generator.

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

Moving from CS 61A Scheme to CS 61B Java

What is a Stack? Stacks and Queues. Stack Abstract Data Type. Java Interface for Stack ADT. Array-based Implementation

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Data Structure with C

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Recursion. Definition: o A procedure or function that calls itself, directly or indirectly, is said to be recursive.

Data Structure and Algorithm I Midterm Examination 120 points Time: 9:10am-12:10pm (180 minutes), Friday, November 12, 2010

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

AFF 808. Sub. Code 4BIT1C1. B.Sc. DEGREE EXAMINATION, NOVEMBER First Semester. Information Technology

Ordered Lists and Binary Trees

Glossary of Object Oriented Terms

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Big O and Limits Abstract Data Types Data Structure Grand Tour.

CompSci-61B, Data Structures Final Exam

Section IV.1: Recursive Algorithms and Recursion Trees

Java Software Structures

Data Structures and Algorithms Written Examination

Exam study sheet for CS2711. List of topics

Algorithms and Data S tructures Structures Stack, Queues, and Applications Applications Ulf Leser

Data Structures in Java. Session 15 Instructor: Bert Huang

Data Structures. Chapter 8

Chapter 8: Bags and Sets

Queues and Stacks. Atul Prakash Downey: Chapter 15 and 16

Chapter 8: Binary Trees

The ADT Binary Search Tree

Software Engineering Techniques

Collaboration policy. Where to get help (but no code in ) Office hours Lab TAs in Friend 008/009 Bounce ideas (but not code) off classmates

Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings:

CmpSci 187: Programming with Data Structures Spring 2015

Data Structures and Algorithms

Symbol Tables. Introduction

Efficient Data Structures for Decision Diagrams

CIS570 Lecture 9 Reuse Optimization II 3

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

14 Stacks, Queues, And Linked Lists

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Habanero Extreme Scale Software Research Project

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Data Structures UNIT III. Model Question Answer

Lecture 12 Doubly Linked Lists (with Recursion)

Recursion and Recursive Backtracking

Structural Design Patterns Used in Data Structures Implementation

Transcription:

Chapter 7 s Developing an ADT 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 2006 Pearson Addison-Wesley. All rights reserved 7A-1 2006 Pearson Addison-Wesley. All rights reserved 7A-2 Developing an ADT During the Design of a Solution Refining the Definition of the ADT 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 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 7A-3 2006 Pearson Addison-Wesley. All rights reserved 7A-4 Refining the Definition of the ADT Pseudocode for the ADT stack operations (Cont) 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 algorithm can be easily accomplished 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 7A-5 2006 Pearson Addison-Wesley. All rights reserved 7A-6

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 Checking for Balanced Braces Requirements for balanced braces Each time you encounter a "{", push it on the stack Each time you encounter a }, it matches an already encountered {, pop "{" off the stack When you reach the end of the string, you should have matched each { and the stack should be empty 2006 Pearson Addison-Wesley. All rights reserved 7A-7 2006 Pearson Addison-Wesley. All rights reserved 7A-8 Checking for Balanced Braces 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 Figure 7-3 Traces of the algorithm that checks for balanced braces 2006 Pearson Addison-Wesley. All rights reserved 7A-9 2006 Pearson Addison-Wesley. All rights reserved 7A-10 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 Implementations of the ADT The ADT stack can be implemented using An array A linked list The ADT list in the JCF Interface Provides a common specification for the three implementations Exception Used by Interface Extends java.lang.runtimeexception 2006 Pearson Addison-Wesley. All rights reserved 7A-11 2006 Pearson Addison-Wesley. All rights reserved 7A-12

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 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 Figure 7-5 An array-based implementation 2006 Pearson Addison-Wesley. All rights reserved 7A-13 2006 Pearson Addison-Wesley. All rights reserved 7A-14 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 A Reference-Based Implementation of the ADT Figure 7-6 A reference-based implementation 2006 Pearson Addison-Wesley. All rights reserved 7A-15 2006 Pearson Addison-Wesley. All rights reserved 7A-16 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) An Implementation That Uses the ADT List Figure 7-7 An implementation that uses the ADT list 2006 Pearson Addison-Wesley. All rights reserved 7A-17 2006 Pearson Addison-Wesley. All rights reserved 7A-18

Comparing Implementations Comparing Implementations 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 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 2006 Pearson Addison-Wesley. All rights reserved 7A-19 2006 Pearson Addison-Wesley. All rights reserved 7A-20 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 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 Example: Evaluating an infix expression Convert the infix expression to postfix form Evaluate the postfix expression 2006 Pearson Addison-Wesley. All rights reserved 7A-21 2006 Pearson Addison-Wesley. All rights reserved 7A-22 Evaluating Postfix Expressions Evaluating Postfix Expressions A postfix calculator Requires you to enter postfix expressions Example: 2 3 4 + * (= 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 7A-23 Figure 7-8 The action of a postfix calculator when evaluating the expression 2 * (3 + 4) 2006 Pearson Addison-Wesley. All rights reserved 7A-24

Evaluating Postfix Expressions 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 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 2006 Pearson Addison-Wesley. All rights reserved 7A-25 2006 Pearson Addison-Wesley. All rights reserved 7A-26 Converting Infix Expressions to Equivalent Postfix Expressions Application: A Search Problem (aka "depth-first" search) 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 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 7A-27 2006 Pearson Addison-Wesley. All rights reserved 7A-28 Representing the Flight Data 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 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-10 Flight map for HPAir 2006 Pearson Addison-Wesley. All rights reserved 7A-29 2006 Pearson Addison-Wesley. All rights reserved 7A-30

A Nonrecursive Solution that Uses a A Nonrecursive Solution that Uses a 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 7A-31 Figure 7-13 A trace of the search algorithm, given the flight map in Figure 6-9 2006 Pearson Addison-Wesley. All rights reserved 7A-32 A Recursive Solution 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 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) } } 2006 Pearson Addison-Wesley. All rights reserved 7A-33 2006 Pearson Addison-Wesley. All rights reserved 7A-34 The Relationship Between s and Recursion Summary 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 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 7A-35 2006 Pearson Addison-Wesley. All rights reserved 7A-36