Queues Chapter 6 Chapter 6: Queues2 Chapter Objectives Learn how to represent a “waiting line”, i.e., a queue Learn how to use the methods in the Queue.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Chapter 6 Queues and Deques.
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Stacks, Queues, and Deques. 2 A stack is a last in, first out (LIFO) data structure Items are removed from a stack in the reverse order from the way they.
Fundamentals of Python: From First Programs Through Data Structures
Queues Briana B. Morrison Adapted from Alan Eugenio.
Queues 4/14/2017 5:24 PM 5.2 Queues Queues Dr Zeinab Eid.
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
Queues Ellen Walker CPSC 201 Data Structures Hiram College.
Today’s Agenda  Stacks  Queues  Priority Queues CS2336: Computer Science II.
CHAPTER 4 Queues. Queue  The queue, like the stack, is a widely used data structure  A queue differs from a stack in one important way  A stack is.
CHAPTER 4 Queues MIDTERM THURSDAY, OCTOBER 17 IN LAB.
1 CSC 211 Data Structures Lecture 22 Dr. Iftikhar Azim Niaz 1.
CSC 212 – Data Structures. Using Stack Stack Limitations  Great for Pez dispensers, JVMs,& methods  All of these use most recent item added only 
Comp 245 Data Structures Queues. Introduction to the Queue ADT It is a FIFO (first-in, first-out) structure Access to the Queue can take place at two.
Queues Chapter 6. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
ITEC200 Week06 Queues. 2 Learning Objectives – Week06 Queues (Ch6) Students can Manage data using the queue Abstract Data Type.
CHAPTER 4 Queues. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
1 Queues Queue Concept Queue Design Considerations Queues in Java Collections APIs Queue Applications Reading L&C , 9.3.
Cmpt-225 Queues. A queue is a data structure that only allows items to be inserted at the end and removed from the front Queues are FIFO (First In First.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Queues Chapter 6. Chapter 6: Queues2 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface.
Chapter 7 Queues. © 2005 Pearson Addison-Wesley. All rights reserved7-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Queues Chapter 8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Cmpt-225 Simulation. Application: Simulation Simulation  A technique for modeling the behavior of both natural and human-made systems  Goal Generate.
Queues What is a Queue? Queue Implementations: Queue As Array
Stacks, Queues, and Deques
EXPANDING STACKS AND QUEUES CS16: Introduction to Data Structures & Algorithms 1 Tuesday, February 10, 2015.
Chapter 17: Stacks and Queues
COMP 121 Week 14: Queues. Objectives Learn how to represent a queue Learn how to use the methods in the Queue interface Understand how to implement the.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
CHP-4 QUEUE.
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
TK1924 Program Design & Problem Solving Session 2011/2012 L6: Queues.
CHAPTER 4 Queues. Chapter Objectives  To learn how to represent a waiting line (queue) and how to use the methods in the Queue interface for insertion.
Lists Based on content from: Java Foundations, 3rd Edition.
Data Structures Using C++ 2E Chapter 8 Queues. Data Structures Using C++ 2E2 Objectives Learn about queues Examine various queue operations Learn how.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 3)
Computer Science 112 Fundamentals of Programming II Modeling and Simulation.
Fall 2007CS 2251 Queues Chapter 6. Fall 2007CS 2252 Chapter Objectives To learn how to represent a waiting line (queue) and how to use the methods in.
Queues Chapter 6. Chapter 6: Queues Chapter Objectives To learn how to represent a waiting line (queue) and how to use the five methods in the Queue interface:
LECTURE 26: QUEUES CSC 212 – Data Structures. Using Stack.
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
Chapter Objectives  Learn how to represent a waiting line (queue)  Become proficient using the methods in the Queue  Understand how to implement the.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Chapter 8 Queues. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear, of.
2005MEE Software Engineering Lecture 7 –Stacks, Queues.
Give Eg:? Queues. Introduction DEFINITION: A Queue is an ordered collection of element in which insertions are made at one end and deletions are made.
CH 5 : STACKS, QUEUES, AND DEQUES ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA.
Onlinedeeneislam.blogspot.com1 Design and Analysis of Algorithms Slide # 1 Download From
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Review Array Array Elements Accessing array elements
Data Structures Using C++ 2E
ADT description Implementations
Queues Queue Concept Queue Design Considerations
Queues Chapter 8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Monday, February 26, 2018 Announcements… For Today…
CMSC 341 Lecture 5 Stacks, Queues
THURSDAY, OCTOBER 17 IN LAB
Cs212: Data Structures Computer Science Department Lecture 7: Queues.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
Chapter 4 Queues.
CSCS-200 Data Structure and Algorithms
Queues.
Chapter 6 – Queues and Deques
Presentation transcript:

Queues Chapter 6

Chapter 6: Queues2 Chapter Objectives Learn how to represent a “waiting line”, i.e., a queue Learn how to use the methods in the Queue interface Insertion (offer and add) Removal (remove and poll) Accessing front element (peek and element) Understand how to implement the Queue interface Double-linked list, single-linked list, circular array Understand how to simulate the operation of a physical system that has one or more waiting lines using queues Also using random number generators

Chapter 6: Queues3 Queue Abstract Data Type A line of customers waiting for service is a queue Q: Who is served next? A: The person who has waited the longest Q: Where do new arrivals go? A: The end of the queue (line)

Chapter 6: Queues4 Uses for Queues Operating systems use queues to manage tasks involving scarce resource Q: Why a queue? A: To ensure that the tasks are carried out in the order that they were generated For example, a print queue Printing is much slower than selecting pages to print

Chapter 6: Queues5 Print Queue

Chapter 6: Queues6 Unsuitability of a Print Stack Stacks are last-in, first-out (LIFO) Most recently selected document would be next to print Unless the printer queue is empty, your print job may never get executed if others are issuing print jobs Queue is better choice for printing Queue since first in, first out (FIFO) “Oldest” selected document gets printed next Much fairer than “print stack”

Chapter 6: Queues7 Queues Used to Traverse Graphs A graph models a network of nodes, with many links connecting each node to other nodes in the network A node in a graph may have several successors Can use a queue to ensure that nodes closer to the starting point are visited before nodes farther away We will see this later…

Chapter 6: Queues8 Specification for a Queue Interface

Chapter 6: Queues9 LinkedList Implements Queue Interface LinkedList provides methods for inserting and removing elements at either end of a double-linked list Java 5.0 LinkedList class implements Queue interface Queue names = new LinkedList (); creates Queue reference, names (in this example, stores references to String objects) The actual object referenced by names is type LinkedList Because names is a type Queue reference, you can apply only the Queue methods to it

Chapter 6: Queues10 Queue Examples Consider Queue names = new LinkedList (); Suppose names currently contains Where “Dorothy” was 1st into the queue Dorothy Toto Scarecrow Tinman Lion

Chapter 6: Queues11 Queue Examples Suppose names currently contains What do each of the following do? String first = names.peek(); String first = names.element(); Dorothy Toto Scarecrow Tinman Lion

Chapter 6: Queues12 Queue Examples Suppose names currently contains What do each of the following do? String temp = names.remove(); String temp = names.poll(); Dorothy Toto Scarecrow Tinman Lion

Chapter 6: Queues13 Queue Examples Suppose names currently contains What do both of the following do? names.offer(“Wizard”); names.add(“Wizard”); Toto Scarecrow Tinman Lion

Chapter 6: Queues14 Queue Examples Then names contains Assuming that only offer or add executed (not both) Toto Scarecrow Tinman Lion Wizard

Chapter 6: Queues15 Case Study: A Queue of Customers Problem: Write menu-driven program that maintains a queue of customers waiting for service. Program must be able to Insert new customer in line Remove customer who is next in line Display length of the line Determine a specific customers place in line

Chapter 6: Queues16 Case Study: A Queue of Customers Analysis: Queue is the obvious choice… Use JOptionPane for dialog menus Inputs: Operation to be performed Name of a customer Outputs: Effect of each operation

Chapter 6: Queues17 Case Study: A Queue of Customers Design: Class MaintainQueue with Queue component, customers Method processCustomers displays menu choices and processes input

Chapter 6: Queues18 Case Study: A Queue of Customers

Chapter 6: Queues19 Case Study: A Queue of Customers Algorithm for processCustomers While the user is not finished Display menu and get selected operation Perform selected operation Each operation requires call to a Queue method Except for finding customer’s place in line How to do this?

Chapter 6: Queues20 Case Study: A Queue of Customers Algorithm for position in queue Get customer’s name Set count of customers ahead to 0 For each customer in the queue If customer is not specified customer Increment count Else Display count and exit loop If all customers examined without success Display message that customer is not in line

Chapter 6: Queues21 Case Study: A Queue of Customers Class file MaintainQueue.java is in the book and at

Chapter 6: Queues22 Queue Implementations We consider 3 different implementations: Double-linked list This is what Java designers used Single-linked list Similar to using double-linked list Circular array Most efficient approach (in terms of space) But somewhat more complex

Chapter 6: Queues23 Double-Linked List Queue Implemention Insertion and removal from either end of a double-linked list is O(1) So either end can be the front (or rear) of the queue Which would you choose? Java makes head of the linked list front of queue So tail is the rear of the queue Issue: LinkedList object is used as a queue Why is this an “issue”? May be possible to apply other LinkedList methods In addition to the ones required by the Queue interface

Chapter 6: Queues24 Single-Linked List Queue Implementation Can implement a queue using a single-linked list Book gives Class ListQueue Contains a collection of Node objects Which end should be front of queue? Front makes sense, that is… insertions are at the rear of a queue and… removals are from the front Want to have a reference to the last list node (why?) Number of elements changed by insert and remove Empty queue is a special case

Chapter 6: Queues25 Single-Linked List Queue Implementation

Chapter 6: Queues26 Circular Array Queue Implementation Time efficiency of using a single- or double-linked list to implement a queue is O(1) However there are some space inefficiencies Storage space is increased when using a linked list due to references stored at each list node Array Implementation: Front and rear? Insertion at rear of array is constant time But them removal from the front is linear time (why?) Removal from rear of array is constant time But then insertion at the front is linear time (why?)

Chapter 6: Queues27 Circular Array Queue Implementation

Chapter 6: Queues28 Circular Array Queue Implementation

Chapter 6: Queues29 Circular Array Queue Implementation

Chapter 6: Queues30 Circular Array Queue Implementation How to access elements in circular array? Use “mod” operator: % For example, to insert (at rear): rear = (rear + 1) % capacity;

Chapter 6: Queues31 Clock Arithmetic arithmetic mod 6 For integers x and n, “x mod n” is the remainder of x  n In Java, “x mod n” is: x % n Examples 7 mod 6 = 1 33 mod 5 = 3 33 mod 6 = 3 51 mod 17 = 0 17 mod 6 = 5

Chapter 6: Queues32 Circular Array Queue Implementation

Chapter 6: Queues33 Circular Array Queue Implementation Why not use System.arraycopy to copy elements when reallocating circular array? System.arraycopy(theData, 0, newData, 0, capacity) This will not work! Consider Toto Scarecrow Tinman Lion Wizard front rear

Chapter 6: Queues34 Circular Array Queue Implementation Suppose to reallocate, we try System.arraycopy(theData, 0, newData, 0, capacity) In this case… Toto Scarecrow Tinman Lion Wizard front rear Toto Scarecrow Tinman Lion Wizard front rear

Chapter 6: Queues35 Implementing Class ArrayQueue.Iter To fully implement the Queue interface… We must implement the missing Queue methods And an inner class Iter Field index has subscript of the next element to access The constructor initializes index to front when a new Iter object is created Data field count keeps track of the number of items accessed so far Method Iter.remove throws Unsupported-OperationException Would violate “contract” by removing item other than 1st

Chapter 6: Queues36 Comparing 3 Queue Implementations All three are O(1), i.e., constant time What about reallocate in circular array? But linked lists require more storage: Why? Extra space for links! Node for single-linked list stores two references Node for double-linked list stores three references How much better is circular array? If filled to capacity, requires half the storage of a single-linked list to store same number of elements

Chapter 6: Queues37 Simulating Waiting Lines Using Queues Simulations used to study the performance of systems Can Use math and/or computer model of system Simulations allow designers of system to estimate performance and/or characteristics before building it Simulation can lead to changes in the design that will improve a proposed system Simulation is useful, for example, when real system is too expensive to build too dangerous to experiment with

Chapter 6: Queues38 Airline Check-In Counter Simulation Two lines/queues: regular passenger and frequent flyers Only one ticket agent How to serve the 2 lines? Democratic strategy: alternate between lines Another democratic strategy: serve longest waiting Elitist approach: serve frequent flyers first Combination strategies Queuing theory can be used to analyze this problem Mathematical theory  also used to study networks Here, we use a computer simulation

Chapter 6: Queues39 Airline Check-In Counter Simulation

Chapter 6: Queues40 Airline Check-In Counter Simulation Problem: Wizard of Oz Airlines is considering redesigning its ticket counter operations Assumptions include One ticket agent Two lines of customers (regular, frequent flyers) Want to experiment with various strategies Democratic, elitist, combinations thereof Want to know effect on waiting time for both lines, under various assumptions on arrival rates

Chapter 6: Queues41 Airline Check-In Counter Simulation Analysis: Computer simulation is a good idea, since difficult to study many alternatives in real world situation Must keep track of “time” Types of “events” that can occur: New frequent flyer arrives in line New regular passenger arrives in line Ticket agent finishes serving someone and begins serving frequent flyer Ticket agent finishes serving someone and begins serving regular passenger Ticket agent is idle (no passengers to serve)

Chapter 6: Queues42 Airline Check-In Counter Simulation Analysis (continued): Purpose is to generate statistics on waiting time for passengers Also, we can display minute-by-minute trace Useful for debugging Results will depend on Priority given to frequent flyers Arrival rate of each type of passenger Time required to serve each passenger

Chapter 6: Queues43 Airline Check-In Counter Simulation Design: Want to identify the objects Look at the nouns: Agent, passengers, passenger lines, simulation Gives us the following UML diagram We will use a queue to represent the “lines” (surprised?)

Chapter 6: Queues44 Airline Check-In Counter Simulation Sequence diagram Shows the flow between objects Also, data that is passed

Chapter 6: Queues45 Airline Check-In Counter Simulation Sequence diagram tells us agent is either busy or idle Also tells us the methods needed in each class Revise UML diagram

Chapter 6: Queues46 Class AirlineCheckinSim

Chapter 6: Queues47 Class AirlineCheckinSim

Chapter 6: Queues48 Class PassengerQueue

Chapter 6: Queues49 Class PassengerQueue

Chapter 6: Queues50 Class Passenger This class stores following info about a passenger Unique ID number Time at which passenger arrived Processing time Maximum processing time Note that “ID number” is just the position in queue

Chapter 6: Queues51 Class Passenger

Chapter 6: Queues52 Input Parameters

Chapter 6: Queues53 Pseudorandom Numbers How to generate “random” numbers? In the real world, flip a coin, roll a die, etc. In computer simulation, use “pseudorandom” numbers Generated in sequence Based on an initial “seed” value Note that same seed yields same sequence Why is this useful (necessary) for computer simulation? Not really “random”, so pseudorandom But these numbers have nice statistical properties

Chapter 6: Queues54 Pseudorandom Numbers Our airline simulation uses pseudorandom numbers to… Determine whether a passenger has arrived within a given minute of simulation Determine how long it takes to serve a passenger Suppose passengers arrival rate is 1 every 5 minutes Do passengers arrive precisely at 0,5,10,15,… ? No! On average, one arrives every 5 minutes How to simulate this?

Chapter 6: Queues55 Pseudorandom Numbers Suppose passengers arrival rate is 1 every 5 minutes For a given 1 minute time interval of simulation Generate pseudorandom number between 0 and 1 If generated number less than 0.2, then passenger arrived in that interval Else no passenger arrived Suppose arrivalRate is rate at which passengers arrive (per minute) Then, in Java, passenger arrives if Math.random() < arrivalRate Otherwise, no passenger arrives

Chapter 6: Queues56 Airline Check-In Counter Simulation Code

Chapter 6: Queues57 Chapter Review Queue is an abstract data type with a first-in, first-out structure (FIFO) The Queue interface declares methods offer, remove, poll, peek, and element. Three ways to implement the Queue interface: double- linked list, single-linked list, and circular array To avoid the cost of building a physical system or running an actual experiment, computer simulation can be used to evaluate the expected performance of a system or operation strategy