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

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

CMPT 225. Stacks-part2

Data Structure Interview Questions

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

Chapter 3 Stack. Books: ISRD Group New Delhi Data structure Using C

CS1150 Principles of Computer Science Methods

Using SPLAY Tree s for state-full packet classification

In Java, we can use Comparable and Comparator to compare objects.

CS1150 Principles of Computer Science Midterm Review

To over come these problems collections are recommended to use. Collections Arrays

- Replacement of a single statement with a sequence of statements(promotes regularity)

1 Binary Trees and Adaptive Data Compression

TRAINING GUIDE. Lucity Mobile


COP2800 Homework #3 Assignment Spring 2013

CS1150 Principles of Computer Science Methods

Design Patterns. Collectional Patterns. Session objectives 11/06/2012. Introduction. Composite pattern. Iterator pattern

Programming Project: Building a Web Server

Principles of Programming Languages

Common Language Runtime

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

Systems & Operating Systems

Project #1 - Fraction Calculator

Chapter 10: Information System Controls for System Reliability Part 3: Processing Integrity and Availability

These tasks can now be performed by a special program called FTP clients.

Objectives. Topic 8: Input, Interaction, & Introduction to callbacks. Input Devices. Project Sketchpad. Introduce the basic input devices

Creating Relativity Dynamic Objects

LAB 7 (June 29/July 4) Structures, Stream I/O, Self-referential structures (Linked list) in C

Lab 1 - Calculator. K&R All of Chapter 1, 7.4, and Appendix B1.2 Iterative Code Design handout Style Guidelines handout

16/07/2012. Design Patterns. By Võ Văn Hải Faculty of Information Technologies - HUI. Behavioral Patterns. Session objectives. Strategy.

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

Lab 4. Name: Checked: Objectives:

Lecture Handout. Database Management System. Overview of Lecture. Vertical Partitioning. Lecture No. 24

Lab 1 - Calculator. K&R All of Chapter 1, 7.4, and Appendix B1.2

ISTE-608 Test Out Written Exam and Practical Exam Study Guide

Vijaya Nallari -Math 8 SOL TEST STUDY GUIDE

Introduction to CS111 Part 2: Big Ideas

Automatic imposition version 5

Structure Query Language (SQL)

Creating Relativity Dynamic Objects

What can we do with Coin dispenser?

STIDistrict AL Rollover Procedures

Computer Organization and Architecture

FIT 100. Lab 10: Creating the What s Your Sign, Dude? Application Spring 2002

Maintaining order. A small student database. Managing databases. Representing table of student data. Sorting and searching

History of Java. VM (Java Virtual Machine) What is JVM. What it does. 1. Brief history of Java 2. Java Version History

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

Lecture Handout. Database Management System. Overview of Lecture. Inheritance Is. Lecture No. 11. Reading Material

STIQuery Basics. A second example is included at the end of this document.

UiPath Automation. Walkthrough. Walkthrough Calculate Client Security Hash

Iteration Part 2. Review: Iteration [Part 1] Flow charts for two loop constructs. Review: Syntax of loops. while continuation_condition : statement1

User Guide. Avigilon Control Center Mobile Version 2.2 for Android

Data Miner Platinum. DataMinerPlatinum allows you to build custom reports with advanced queries. Reports > DataMinerPlatinum

CS1150 Principles of Computer Science Boolean, Selection Statements (Part II)

MOS Access 2013 Quick Reference

The Mathematics of the Rubik s Cube

CS1150 Principles of Computer Science Introduction (Part II)

Dear Milestone Customer,

Chapter 2 Assemblers. PDF created with FinePrint pdffactory Pro trial version

What s New in Banner 9 Admin Pages: Differences from Banner 8 INB Forms

TIBCO Statistica Options Configuration

Relational Operators, and the If Statement. 9.1 Combined Assignments. Relational Operators (4.1) Last time we discovered combined assignments such as:

Creating Relativity Dynamic Objects

1 Version Spaces. CS 478 Homework 1 SOLUTION

Constituent Page Upgrade Utility for Blackbaud CRM

Instance Based Learning

CS510 Concurrent Systems Class 2. A Lock-Free Multiprocessor OS Kernel

Java Programming Course IO

McGill University School of Computer Science COMP-206. Software Systems. Due: September 29, 2008 on WEB CT at 23:55.

24-4 Image Formation by Thin Lenses

SAS Viya 3.2 Administration: Mobile Devices

CSE 3320 Operating Systems Deadlock Jia Rao

Cisco Tetration Analytics, Release , Release Notes

Outlook Web Application (OWA) Basic Training

Paraben s Phone Recovery Stick

FREE UP SPACE ON YOUR C: DRIVE IN "WINDOWS.."

Lesson 4 Advanced Transforms

1 Getting and Extracting the Upgrader

* The mode WheelWork starts in can be changed using command line options.

Announcing Veco AuditMate from Eurolink Technology Ltd

Two-Dimensional Topology Structure between Vector Layers in GIS

DECISION CONTROL CONSTRUCTS IN JAVA

Lab 5 Sorting with Linked Lists

Beyond Verification. Software Synthesis

Last time: search strategies

Word 2007 The Ribbon, the Mini toolbar, and the Quick Access Toolbar

UiPath Automation. Walkthrough. Walkthrough Calculate Client Security Hash

Chapter 6 Delivery and Routing of IP Packets. PDF created with FinePrint pdffactory Pro trial version

CS1150 Principles of Computer Science Final Review

Querying Data with Transact SQL

Date Lesson TOPIC Homework. Parametric and Vector Equations of a Line in R 2 Pg. 433 # 2 6, 9, 11. Vector and Parametric Equation of a Plane in Space

Troubleshooting of network problems is find and solve with the help of hardware and software is called troubleshooting tools.

Xilinx Answer Xilinx PCI Express DMA Drivers and Software Guide

You try: Find an equivalent fraction. 1 Find an equivalent fraction to 4. Model: Model: 6. Multiply by a Form of One: 8


CITI Technical Report 08-1 Parallel NFS Block Layout Module for Linux

Administrativia. Assignment 1 due tuesday 9/23/2003 BEFORE midnight. Midterm exam 10/09/2003. CS 561, Sessions 8-9 1

ECE 545 Project Deliverables

Access the site directly by navigating to in your web browser.

CMU 15-7/381 CSPs. Teachers: Ariel Procaccia Emma Brunskill (THIS TIME) With thanks to Ariel Procaccia and other prior instructions for slides

Transcription:

The Abstract Data Type Stack Simple Applicatins f the ADT Stack Implementatins f the ADT Stack Applicatins 1

The Abstract Data Type Stack 3 ADT STACK Examples readandcrrect algrithm abcc ddde ef fg Output: abcdefg Hw can a prgram read the riginal line and get the crrect input? Hw t stre the input line? ADT apprach, pstpne decisin fr cnsidering what peratins yu will need t perfrm n the data? 2

ADT STACK The Abstract Data Type: readandcrrect algrithm Read the line, crrecting mistakes alng the way abcc ddde ef fg Add a new item t the ADT Remve frm the ADT the item that was added mst recently Determine whether the ADT is empty Retrieve frm the ADT the item that was added mst recently while(nt end end f f input){ input){ read a new new character ch ch if(ch is is nt nt a a ){ ){ Add ch t the ADT Add ch t the ADT else if ( the ADT is nt empty ){ else { remve frm the ADT the item added mst recently remve frm the ADT the item added mst recently else { Ignre the ADT STACK 3

ADT STACK ADT stack peratins Create an empty stack Determine whether a stack is empty Add a new item t the stack Remve frm the stack the item that was added mst recently Remve all the items frm the stack Retrieve frm the stack the item that was added mst recently ADT STACK Pseudcde fr the ADT stack peratins createstack() // Creates an empty stack. isempty() // Determines whether a stack is empty. push(newitem) thrws StackExceptin // Adds newitem t the tp f the stack. // Thrws StackExceptin if the insertin is nt successful. pp() thrws StackExceptin // Retrieves and then remves the tp f the stack. // Thrws StackExceptin if the deletin is nt successful. ppall() // Remves all items frm the stack. peek() thrws StackExceptin // Retrieves the tp f the stack. Thrws StackExceptin if the retrieval is nt successful Stack tp items createstack() isempty() push() pp() ppall() peek() 4

ADT STACK A stack Last-in, first-ut (LIFO) prperty The last item placed n the stack will be the first item remved Analgy A stack f dishes in a cafeteria ADT STACK Using the ADT Stack in a Slutin readandcrrect() Read the input line and returns the crrected versin as a stack astack.createstack(); Read newchar While (newchar is nt the end-f-line symbl) { if (newchar is nt a ){ astack.push(newchar) else if (!astack.isempty( )){ ldchar=astack.pp( ) Read newchar retuen astack 5

ADT STACK Thinking Example: S.pp(); S.push(c); S.push(b); S.pp(); S.peek(); S.push(a); S.peek(); S.push(b); S.pp(); S.push(c); Simple Applicatins f the ADT Stack 12 6

SIMPLE APPLICATIONS Checking the balanced braces A stack can be used t verify whether a prgram cntains balanced braces An example f balanced braces abc{defg{ijk{l{mnpqr An example f unbalanced braces abc{def{ghij{klm Requirements fr balanced braces Each time yu encunter a, it matches an already encuntered { When yu reach the end f the string, yu have matched each { Each successive clse brace with the mst recently encuntered unmatched pen brace { SIMPLE APPLICATIONS Checking the balanced braces astack.createstack(); balancedsfar= true; i=0; while(balancedsfar and i<length f astring){ ch=character at psitin i in astring; ++i; If(ch is { )// push an pen brace { astack.push( { ); else if (ch is )//clse brace { if(!astack.isempty()) { penbrace=astack.pp();//pp a matching pen brace else{ balancedsfar=false; 7

SIMPLE APPLICATIONS Checking the balanced braces SIMPLE APPLICATIONS Recgnizing Strings in a Language Language L L = {w$w : w is a pssible empty string f characters ther than $, w = reverse(w) A stack can be used t determine whether a given string is in L Traverse the first half f the string, pushing each character nt a stack Once yu reach the $, fr each character in the secnd half f the string, pp a character ff the stack Match the ppped character with the current character in the string 8

SIMPLE APPLICATIONS Thinking L = {w$w: w is a pssible empty string f characters ther than $ e.g. ab$ab, aacc$aacc, aacc$ccaa Can we use stack t verify the string by scanning the string nly nce? Why? Implementatins f the ADT Stack 18 9

Implementatins f the ADT stack The ADT stack can be implemented using StackExceptin Stack tp items An array createstack() isempty() A linked list push() The ADT list pp() ppall() StackInterface peek() Prvides a cmmn specificatin fr all implementatins Implementatins f the ADT stack Array-based implementatin f the ADT stack StackArrayBased class Implements StackInterface Instances Stacks Private data fields An array f Objects called items The index tp Cnstructr replaces the ADT peratin createstack Stack tp items createstack() isempty() push() pp() ppall() peek() 10

Implementatins f the ADT stack A reference-based implementatin f the ADT stack Required when the stack needs t grw and shrink dynamically StackReferenceBased Implements StackInterface tp is a reference t the head f a linked list f items Stack tp items createstack() isempty() push() pp() ppall() peek() Implementatins f the ADT stack ADT list-based implementatin f the ADT stack The ADT list can be used t represent the items in a stack If the item in psitin 1 f a list represents the tp f the stack push(newitem) peratin is implemented as add(0, newitem) pp() peratin is implemented as get(0) remve(0) peek() peratin is implemented as get(0) Stack tp items createstack() isempty() push() pp() ppall() peek() 11

Cmparisn All f the three implementatins are ultimately array based r reference based Fixed size versus dynamic size An array-based implementatin Uses fixed-sized arrays Prevents the push peratin frm adding an item t the stack if the stack s size limit has been reached A reference-based implementatin Des nt put a limit n the size f the stack ADT list apprach Reuses an already implemented class Much simpler t write Saves time JCF JCF cntains an implementatin f a stack class called Stack (generic) java.util.stack Derived frm Vectr Includes methds: empty, peek, pp, push, and search search returns the 1-based psitin f an bject n the stack 12

Applicatins 25 Applicatins Algebraic Expressins T evaluate an infix expressins Cnvert the infix expressin t pstfix frm Evaluate the pstfix expressin 13

Applicatins Evaluating Pstfix Expressins A pstfix calculatr Requires yu t enter pstfix expressins Example: 2, 3, 4, +, * When an perand is entered, the calculatr Pushes it nt a stack When an peratr is entered, the calculatr Applies it t the tp tw perands f the stack Pps the perands frm the stack Pushes the result f the peratin n the stack Applicatins 14

Applicatins Evaluating Pstfix Expressins T evaluate a pstfix expressin which is entered as a string f characters Simplifying assumptins The string is a syntactically crrect pstfix expressin N unary peratrs are present N expnentiatin peratrs are present Operands are single lwercase letters that represent integer values Applicatins Cnverting Infix Expressins t Equivalent Pstfix Expressins Facts abut cnverting frm infix t pstfix Operands always stay in the same rder with respect t ne anther An peratr will mve nly t the right with respect t the perands All parentheses are remved 15

Applicatins Initialize pstfixexp t the null string fr (each character ch in the infix expressin){ switch(ch){ case ch is an perand: append ch t the end f pstfixexp break; case ch is ( : astack.push(ch) break; case ch is ) : While (tp f stack is bt ( ){ pstfixexp=pstfixexp+astack.pp(); penparen=astack.pp(); //remve the pen parenthesis break; case ch is an peratr: while(!astack.isempty() and tp f stack is nt ( and precedence(ch)<= precedence(tp f stack)) { pstfixexp=pstfixexp+astack.pp(); astack.push(ch) //save new peratr break; while(!astack.isempty()){ pstfixexp=pstfixexp+astack.pp(); Applicatins Cnverting Infix Expressins t Equivalent Pstfix Expressins a-(b+c*d)/e 16

Applicatins High Planes Airline Cmpany (HPAir) Prblem Fr each custmer request, indicate whether a sequence f HPAir flights exists frm the rigin city t the destinatin city The flight map fr HPAir is a directed graph Adjacent vertices: tw vertices that are jined by an edge Directed path: a sequence f directed edges Applicatins The slutin perfrms an exhaustive search Beginning at the rigin city, the slutin will try every pssible sequence f flights until either It finds a sequence that gets t the destinatin city It determines that n such sequence exists The ADT stack is useful in rganizing an exhaustive search Backtracking can be used t recver frm a wrng chice f a city 17

Applicatins Pssible utcmes f the recursive search strategy Yu eventually reach the destinatin city and can cnclude that it is pssible t fly frm the rigin t the destinatin Yu reach a city C frm which there are n departing flights Stacks and Recursin The relatinship between stacks and recursin A cmparisn f key aspects f tw search algrithms Visiting a new city Recursive call vs. push stack Backtracking an unvisited city that is adjacent t the current city Frmal parameter vs. tp f stack Terminatin Bx trace terminate and result returned vs. stack empty r tp is destinatin 18

Stacks and Recursin The relatinship between stacks and recursin ADT stack has a hidden presence in the cncept f recursin Stacks are used t implement recursive methds Each recursive call generates an activatin recrd that is pushed nt a stack Yu can use stacks when implementing a nnrecursive versin f a recursive algrithm HOMEWORK Read thrugh Chapter 7 19