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

Similar documents
csci 210: Data Structures Stacks and Queues

Stacks and Queues

16-Dec-10. Collections & Data Structures ABSTRACTION VS. IMPLEMENTATION. Abstraction vs. Implementation

Data Abstraction and Specification of ADTs

Basic Data Structures

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

ECE 122. Engineering Problem Solving with Java

Basic Data Structures 1 / 24

CS159. Nathan Sprague

Stacks. Revised based on textbook author s notes.

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

Errors and Exceptions

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

CS159. Nathan Sprague

Data Structures G5029

Lists are great, but. Stacks 2

CSE 143. Lecture 4: Stacks and Queues

Exceptions and Design

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

BBM 102 Introduction to Programming II Spring Exceptions

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exceptions in Java

Object Oriented Programming

COSC160: Data Structures: Lists and Queues. Jeremy Bolton, PhD Assistant Teaching Professor

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

CS 221 Review. Mason Vail

CSC148 Week 2. Larry Zhang

Name CPTR246 Spring '17 (100 total points) Exam 3

Lecture 3: Stacks & Queues

CSC 1052 Algorithms & Data Structures II: Stacks

Precept 2: Data structures, Searching, and Sorting. Qian Zhu Feb 8, 2011

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

COS226 - Spring 2018 Class Meeting # 21 April 23, 2018

Exceptions Handling Errors using Exceptions

LIFO : Last In First Out

Building Java Programs

BBM 102 Introduction to Programming II Spring 2017

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

STACKS AND QUEUES. Problem Solving with Computers-II

Exceptions. Examples of code which shows the syntax and all that

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

CT 229 Object-Oriented Programming Continued

Stacks and Queues. Introduction to abstract data types (ADTs) Stack ADT. Queue ADT. Time permitting: additional Comparator example

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

COMP1008 Exceptions. Runtime Error

Object Oriented Programming Exception Handling

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Chapter 5. ADTs Stack and Queue

CS 206 Introduction to Computer Science II

CSCI-142 Exam 2 Review November 2, 2018 Presented by the RIT Computer Science Community

Data Structure. Recitation IV

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

C16b: Exception Handling

CS 216 Exam 1 Fall SOLUTION

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CS 206 Introduction to Computer Science II

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

Correctness and Robustness

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Java Errors and Exceptions. Because Murphy s Law never fails

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

CSE 143 SAMPLE MIDTERM

National University. Faculty of Computer Since and Technology Object Oriented Programming

EXCEPTIONS. Java Programming

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

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

Object Oriented Programming

Lecture 19 Programming Exceptions CSE11 Fall 2013

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Exceptions. Gunnar Gotshalks EX 1

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Chapter 13 Exception Handling

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

Problem 1: Building and testing your own linked indexed list

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Fundamentals of Object Oriented Programming

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Programming Abstractions

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

Programming II (CS300)

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

CSCI 200 Lab 4 Evaluating infix arithmetic expressions

Project 1: Implementation of the Stack ADT and Its Application

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Exception-Handling Overview

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Stacks, Queues & Trees. The Stack Interface. The Stack Interface. Harald Gall, Prof. Dr.

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

Data Structures. 02 Exception Handling

Introduction to Programming Using Java (98-388)

Queues Fall 2018 Margaret Reid-Miller

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

Name Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Transcription:

Stacks and Queues Gregory D. Weber CSCI C243 Data Structures

Principal Points 1. The Stack interface: how to declare it, what it does. 2. Generics: why they were added to Java, how to use them. 3. The call stack: how it supports execution of method calls. 4. Exceptions: what are they, how to use them. 5. The Queue interface: how to declare it, what it does.

Stacks and Queues Stacks and queues are similar: both are collections ordered by time of insertion. Differences: stacks allow access to the most recently inserted element; queues, least recently inserted. We study the stack and queue ADTs, deferring implementations

4.1 Stack Interface v. 1 Top of stack Fig. 4-1, p. 88 Operations: push, pop, peek, isempty LIFO (Last In, First Out): remove elements in opposite order from insertion The interface declaration, version 1 (non-generic, i.e., a stack of Objects): Fig. 4-2 pp. 88 89

The Class java.util.stack Drake presents stack ADT as an interface Java standard library includes class java.util.stack Find its documentation in Java API documentation. How does it compare? Still an abstract data type for us

Generics Motivation Generic types (classes and interfaces) introduced in Java 1.5. Parametric types A generic type has one or more type parameters, typically specifying the types of elements it can contain. public class Stack<E> In constructors and methods E For stacks, E represents the type of elements To make a stack of Integers: Stack<Integer> s = new Stack<Integer>(); Default: E is Object

Generic Stack Interface (v. 2) Code, Fig. 4-2 p. 90 Compare to version 1 Instantiating the generic type: error on p. 89 Stack<Die> s = new Stack<Die>(); We cannot instantiate an interface We must instantiate a class Stack<Die> s = new StackImpl<Die> ();

Evaluating Generic Types Advantages Stricter type checking Cannot push Beetle onto Stack<Die> Avoid ugly casts Stack mystack =...; mystack.push(new Beetle()); Beetle tony = (Beetle) (mystack.pop()); Disadvantages More syntax, additional complexity Type parameters exist only at compile time Generic types are an option

Example Reversing the order of words in a message, using a stack: Reverse.java

4.2 The Call Stack How to call methods with local variables? main (args) A(x, y) B(y, z) C(z, w) Two problems arise: 1. Avoid conflict of common variable names 2. Where should each method return to?

Recursive Method Calls (same problems, more intense) main(args) fact(n) fact(n) fact(n)

Solution: the Call Stack A stack of call frames (activation records) Each call frame represents a method call Stores parameters, other local variables Stores return address Fig. 4-16 p. 99: explain in detail. Identify the call frames. Usually ignore the call stack, but... It sheds light on recursion and Java error messages

Interpreting a Stack Trace See Fig. 4-17 p. 100 Interpret the stack trace. Focus programmer s attention on two methods Where the exception occurred The method that called that one

Lab 2: Postfix Calculator p. 116, Project 4.20 Demonstrate the desktop calculator dc p prints top of stack( peek ) [Hello world]p prints Hello world Control-D to exit

Break

4.3 Exceptions Graceful handling of anomalies Compare with assertions Errors Throwing Catching Not catching

Exceptions Are Objects Many kinds Exception ArithmeticException NullPointerException ArrayIndexOutOfBoundsException Defining our own public class IllegalMoveException extends Exception { }

Throwing Exceptions 1. Declare the method throws RottenEggException 2. Javadoc comment the exception with keyword @throws 3. Write code to create and throw exception if (...) throw new RottenEggException(); 4. Example: deal method in IdiotsDelight.java (Fig. 4-20 p. 102)

Calling Methods That Throw Exceptions Two choices: 1. Pass the buck Caller must declare throws RottenEggException unless it s a RuntimeException 2. Catch exception using a try/catch statement: try {... } catch (RottenEggException e) {... // handle exception e }

Things to Do with a Caught Exception Try to correct the error Print stack trace; exit with error code: e.printstacktrace(); System.exit(1); Return codes: 0 = okay, true; non-zero = error, false

Examining the Return Code Using bash or similar shells With logical operators $ java MyRottenEggClass echo "something s wrong" $ java MyRottenEggClass && echo "success!" With the if statement $ if java MyRottenEggClass; then echo "Hooray!" else echo "Boo-hoo" fi Examining the shell variable $? $ java MyRottenEggClass $ echo $?

A Few of the Exception Classes (page 107) Exception IllegalMoveException RuntimeException EmptyStructureException ArithmeticException NullPointerException ArrayIndexOutOfBoundsException Methods need not declare throwing RuntimeExceptions

4.4 Queues Queues are FIFO collections First In, First Out Opposite of stack

Queue Interface Queue.java (page 109, Figure 4-30)

Queue Methods Preferred names: enqueue for add, and dequeue for remove. How to remember: enqueue as in enter (enter queue) dequeue as in depart (depart queue) Could add a front method, analogous to peek for stacks

A Queue Example A queue to manage printing: Printing.java