LECTURE OBJECTIVES 6-2

Similar documents
Queue rear tail front head FIFO

Announcements Queues. Queues

A queue is a linear collection whose elements are added on one end and removed from the other

ITI Introduction to Computing II

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

ECE Fall st Midterm Examination (120 Minutes, closed book)

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

Ashish Gupta, Data JUET, Guna

LIFO : Last In First Out

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

CSC 1052 Algorithms & Data Structures II: Linked Queues

Queues Fall 2018 Margaret Reid-Miller

CSEN 301 Data Structures and Algorithms

(6-1) Basics of a Queue. Instructor - Andrew S. O Fallon CptS 122 (September 26, 2018) Washington State University

Stack and Queue. Stack:

CS24 Week 4 Lecture 2

How can we improve this? Queues 6. Topological ordering: given a sequence of. should occur prior to b, provide a schedule. Queues 5.

Lecture Data Structure Stack

Abstract Data Types. Abstract Data Types

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CE204 Data Structures and Algorithms Part 2

Stacks and Queues III

CS 231 Data Structures and Algorithms Fall DDL & Queue Lecture 20 October 22, Prof. Zadia Codabux

CMSC 132: Object-Oriented Programming II. Stack and Queue

CSC 1052 Algorithms & Data Structures II: Queues

CS302 - Data Structures using C++

Queues COL 106. Slides by Amit Kumar, Shweta Agrawal

csci 210: Data Structures Stacks and Queues

Queues. Data structures that wait their turn. queues 1

More Data Structures (Part 1) Stacks

COMP 213 Advanced Object-oriented Programming Lecture 8 The Queue ADT (cont.)

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

Basic Data Structures

Circular Queue can be created in three ways they are: Using single linked list Using double linked list Using arrays

Stacks. Stacks. Main stack operations. The ADT Stack stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) principle.

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Queues. Stacks and Queues

Introduction to Computer Science II (CSI 1101) Final Examination

Basic Data Structures 1 / 24

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

Linked Structures - Review Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Queues 4/11/18. Many of these slides based on ones by Cynthia Lee

Lists. ordered lists unordered lists indexed lists 9-3

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

SCJ2013 Data Structure & Algorithms. Queue. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi

CS 206 Introduction to Computer Science II

Queue ADT. January 31, 2018 Cinda Heeren / Geoffrey Tien 1

ITI Introduction to Computing II

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

CSC 273 Data Structures

Keeping Order:! Stacks, Queues, & Deques. Travis W. Peters Dartmouth College - CS 10

Stacks and Queues

Lecture 3: Queues, Testing, and Working with Code


Data Abstraction and Specification of ADTs

Queues. Virtuelle Fachhochschule. Prof. Dr. Debora Weber-Wulff

Stacks and Queues. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Queue with Array Implementation

Chapter 2. Stack & Queues. M hiwa ahmad aziz

STACKS AND QUEUES. Problem Solving with Computers-II

1 P age DS & OOPS / UNIT II

CMSC Introduction to Algorithms Spring 2012 Lecture 7

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

DEEPIKA KAMBOJ UNIT 2. What is Stack?

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

1. Introduction. Lecture Content

Queues. October 20, 2017 Hassan Khosravi / Geoffrey Tien 1

Queue. COMP 250 Fall queues Sept. 23, 2016

Stacks and Queues. David Greenstein Monta Vista

Week 6. Data structures

Building Java Programs

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

All the above operations should be preferably implemented in O(1) time. End of the Queue. Front of the Queue. End Enqueue

Soda Machine Laboratory

Introduction to Data Structures and Algorithms

The Stack ADT. Stacks and Queues. Stack: Illustration. What is a Stack? Accessors top size isempty

Queues. ADT description Implementations. October 03, 2017 Cinda Heeren / Geoffrey Tien 1

Information Science 2

Queue: Queue Representation: Basic Operations:

Ch. 18: ADTs: Stacks and Queues. Abstract Data Type

Data Structures. Lecture 5 : The Queues

Topic 2. Collections

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

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

CMSC 341 Lecture 7 Lists

infix expressions (review)

data structures and algorithms lecture 6

Queues. Data Structures and Design with Java and JUnit Rick Mercer 18-1

CmpSci 187: Programming with Data Structures Spring 2015

Data Structures. Alice E. Fischer. Lecture 4, Fall Alice E. Fischer Data Structures L4... 1/19 Lecture 4, Fall / 19

CSE 143. Lecture 4: Stacks and Queues

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

CS 1114: Implementing Search. Last time. ! Graph traversal. ! Two types of todo lists: ! Prof. Graeme Bailey.

Chapter 18: Stacks And Queues

Final Exam Data Structure course. No. of Branches (5)

Stacks and Queues as Collections

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

Data Structures and Algorithms for Engineers

Transcription:

The Queue ADT

LECTURE OBJECTIVES Examine queue processing Define a queue abstract data type Demonstrate how a queue can be used to solve problems Examine various queue implementations Compare queue implementations 6-2

QUEUES Queue: a collection whose elements are added at one end (the rear or tail of the queue) and removed from the other end (the front or head of the queue) A queue is a FIFO (first in, first out) data structure Any waiting line is a queue: The check-out line at a grocery store The cars at a stop light An assembly line 6-3

CONCEPTUAL VIEW OF A QUEUE Adding an element Front of queue New element is added to the rear of the queue 6-4

CONCEPTUAL VIEW OF A QUEUE Removing an element New front element of queue Element is removed from the front of the queue 6-5

USES OF QUEUES IN COMPUTING For any kind of problem involving FIFO data Printer queue (e.g. printer in MC 235) Keyboard input buffer GUI event queue (click on buttons, menu items) To encode messages (more on this later) 6-6

Uses of Queues in Computing In simulation studies, where the goal is to reduce waiting times: Optimize the flow of traffic at a traffic light Determine number of cashiers to have on duty at a grocery store at different times of day Other examples? 6-7

QUEUE OPERATIONS enqueue : add an element to the tail of a queue dequeue : remove an element from the head of a queue first : examine the element at the head of the queue ( peek ) Other useful operations (e.g. is the queue empty) It is not legal to access the elements in the middle of the queue! 6-8

OPERATIONS ON A QUEUE Operation Description dequeue enqueue first isempty size tostring Removes an element from the front of the queue Adds an element to the rear of the queue Examines the element at the front of the queue Determines whether the queue is empty Determines the number of elements in the queue Returns a string representation of the queue 6-9

THE QUEUEADT INTERFACE IN UML <<interface>> QueueADT dequeue( ) enqueue( ) first( ) isempty( ) size( ) tostring( ) 6-10

INTERFACE TO A QUEUE IN JAVA public interface QueueADT<T> { // Adds one element to the rear of the queue public void enqueue (T element); // Removes and returns the element at the front of the queue public T dequeue( ); // Returns without removing the element at the front of the queue public T first( ); // Returns true if the queue contains no elements public boolean isempty( ); // Returns the number of elements in the queue public int size( ); // Returns a string representation of the queue public String tostring( ); } 6-11

USING QUEUES: CODED MESSAGES A Caesar cipher is a substitution code that encodes a message by shifting each letter in a message by a constant amount k If k is 5, a becomes f, b becomes g, etc. Example: n qtaj ofaf Used by Julius Caesar to encode military messages for his generals (around 50 BC) This code is fairly easy to break! 6-12

Using Queues: Coded Messages Modern version: ROT13 Each letter is shifted by 13 used in online forums as a means of hiding spoilers, punchlines, puzzle solutions, and offensive materials from the casual glance (Wikipedia) What is the advantage of shifting 13? Hint ROT13(A) = N, ROT13(N) = A 6-13

USING QUEUES: CODED MESSAGES An improvement: change how much a letter is shifted depending on where the letter is in the message A repeating key is a sequence of integers that determine how much each character is shifted Example: consider the repeating key 3 1 7 4 2 5 The first character in the message is shifted by 3, the next by 1, the next by 7, and so on When the key is exhausted, start over at the beginning of the key 6-14

AN ENCODED MESSAGE USING A REPEATED KEY Encoded message n o v a n g j h l m u u r x l v Key 3 1 7 4 2 5 3 1 7 4 2 5 3 1 7 4 k n o w l e d g e i s p o w e r Decoded message 6-15

Using Queues: Coded Messages We can use a queue to store the values of the key dequeue a key value when needed After using it, enqueue it back onto the end of the queue So, the queue represents the constantly cycling values in the key 6-16

USING QUEUES: CODED MESSAGES See Codes.java Note that there are two copies of the key, stored in two separate queues The encoder has one copy The decoder has a separate copy Why? 6-17

UML DESCRIPTION OF CODES PROGRAM CircularArrayQueue front rear enqueue( ) dequeue( ) first( ) isempty( ) size( ) tostring( ) <<interface>> QueueADT enqueue( ) dequeue( ) first( ) isempty( ) size( ) tostring( ) Codes main () 6-18

USING QUEUES: TICKET COUNTER SIMULATION Simulate the waiting line at a movie theatre: Determine how many cashiers are needed to keep the customer wait time under 7 minutes Assume: Customers arrive on average every 15 seconds Processing a request takes two minutes once a customer reaches a cashier See Customer.java, TicketCounter.java 6-19

UML DESCRIPTION OF TICKETCOUNTER PROGRAM LinkedQueue front rear enqueue( ) dequeue( ) first( ) isempty( ) size( ) tostring( ) <<interface>> QueueADT enqueue( ) dequeue( ) first( ) isempty( ) size( ) tostring( ) Customer TicketCounter PROCESS MAX_CASHIERS NUM_CUSTOMERS main() arrivaltime departuretime Customer(int arrives) getarrivaltime( ) setdeparturetime( ) getdeparturetime( ) totaltime( ) 6-20

RESULTS OF TICKET COUNTER SIMULATION Number of Cashiers 1 2 3 4 5 6 7 8 9 10 5317 2325 1332 840 547 355 219 120 120 120 Average time (in seconds) 6-21

QUEUE IMPLEMENTATION ISSUES What do we need to implement a queue? A data structure (container) to hold the data elements Something to indicate the front of the queue Something to indicate the end of the queue 6-22

QUEUE IMPLEMENTATION USING A LINKED LIST Internally, the queue is represented as a linked list of nodes, with each node containing a data element We need two pointers for the linked list A pointer to the beginning of the linked list (front of queue) A pointer to the end of the linked list (rear of queue) We will also have a count of the number of items in the queue 6-23

LINKED IMPLEMENTATION OF A QUEUE A queue q containing four elements q rear front 4 count. 6-24

Discussion What if the queue is empty? What if there is only 1 element? 6-25

QUEUE AFTER ADDING ELEMENT New element is added in a node at the end of the list, rear points to the new node, and count is incremented q rear front 5 count. 6-26

QUEUE AFTER A DEQUEUE OPERATION Node containing is removed from the front of the list (see previous slide), front now points to the node that was formerly second, and count has been decremented. q rear front 4 count. 6-27

JAVA IMPLEMENTATION The queue is represented as a linked list of nodes: We will again use the LinearNode class front is a reference to the head of the queue (beginning of the linked list) rear is a reference to the tail of the queue (end of the linked list) The integer count is the number of nodes in the queue 6-28

public class LinkedQueue<T> implements QueueADT<T> { /** * Attributes */ private int count; private LinearNode<T> front, rear; /** * Creates an empty queue. */ public LinkedQueue() { count = 0; front = rear = null; } The LinkedQueue class 6-29

//----------------------------------------------------------------- // Adds the specified element to the rear of the queue. //----------------------------------------------------------------- public void enqueue (T element) { LinearNode<T> node = new LinearNode<T> (element); } if (isempty( )) front = node; else rear.setnext (node); rear = node; count++; The enqueue( ) operation 6-30

//----------------------------------------------------------------- // Removes the element at the front of the queue and returns a // reference to it. Throws an EmptyCollectionException if the // queue is empty. //----------------------------------------------------------------- public T dequeue ( ) throws EmptyCollectionException { if (isempty( )) throw new EmptyCollectionException ("queue"); T result = front.getelement( ); front = front.getnext( ); count--; if (isempty( )) rear = null; return result; } The dequeue( ) operation 6-31

ARRAY IMPLEMENTATION OF A QUEUE First Approach: Use an array in which index 0 represents one end of the queue (the front) Integer value rear represents the next open slot in the array (and also the number of elements currently in the queue) Discussion: What is the challenge with this approach? 6-32

AN ARRAY IMPLEMENTATION OF A QUEUE A queue aq containing four elements aq queue 4 rear front 0 1 2 3 4? 6-33

QUEUE AFTER ADDING AN ELEMENT Element is added at the array location given by the (old) value of rear, and then rear is incremented. aq queue 5 rear 0 1 2 3 4 6-34

QUEUE AFTER REMOVING AN ELEMENT Element is removed from array location 0, remaining elements are shifted forward one position in the array, and then rear is decremented. aq queue 4 rear 0 1 2 3 4. 6-35

JAVA ARRAY IMPLEMENTATION See ArrayQueue.java 6-36

public class ArrayQueue<T> implements QueueADT<T> { private final int DEFAULT_CAPACITY = 100; private int rear; private T[] queue; public ArrayQueue() { rear = 0; The ArrayQueue class queue = (T[])(new Object[DEFAULT_CAPACITY]); } public ArrayQueue (int initialcapacity) { rear = 0; queue = (T[])(new Object[initialCapacity]); } 6-37

//----------------------------------------------------------------- // Adds the specified element to the rear of the queue, // expanding the capacity of the queue array if // necessary. //----------------------------------------------------------------- public void enqueue (T element) { if (size() == queue.length) expandcapacity( ); queue[rear] = element; rear++; } The enqueue( ) operation 6-38

//----------------------------------------------------------------- // Removes the element at the front of the queue and returns // a reference to it. Throws anemptycollectionexception if the // queue is empty. //----------------------------------------------------------------- public T dequeue ( ) throws EmptyCollectionException { if (isempty( )) throw new EmptyCollectionException ("queue"); T result = queue[0]; rear--; // shift the elements for (int i = 0; i < rear; i++) queue[i] = queue[i+1]; queue[rear] = null; return result; } The dequeue( ) operation 6-39

SECOND APPROACH: QUEUE AS A CIRCULAR ARRAY If we don't fix one end of the queue at index 0, we won't have to shift elements Circular array is an array that conceptually loops around on itself The last index is thought to precede index 0 In an array whose last index is n, the location before index 0 is index n; the location after index n is index 0 Need to keep track of where the front as well as the rear of the queue are at any given time 6-40

Conceptual Example of a Circular Queue front 0 1 After 7 enqueues 0 1 After 5 dequeues 12 12 front 11 10 rear 11 10 rear 0 1 rear 12 11 10 front After 8 more enqueues 6-41

CIRCULAR ARRAY IMPLEMENTATION OF A QUEUE cq 3 front queue 0 1 2 3 4 5 8 rear 5 count n-1 n-2 6 7 n-3... 10 9 8 6-42

A QUEUE STRADDLING THE END OF A CIRCULAR ARRAY cq 98 front queue 0 1 2 3 4 5 2 rear 4 count 99 98 6 7 97 8... 10 9 6-43

CIRCULAR QUEUE DRAWN LINEARLY Queue from previous slide 98 cq front 2 queue 4 0 1 2 3 4 96 97 98 99 rear count 6-44

CIRCULAR ARRAY IMPLEMENTATION When an element is enqueued, the value of rear is incremented But it must take into account the need to loop back to index 0: rear = (rear+1) % queue.length; Can this array implementation also reach capacity? 6-45

EXAMPLE: ARRAY OF LENGTH 4 WHAT HAPPENS? 0 1 2 3 2 cq front 1 rear queue 3 count Suppose we try to add one more item to a queue implemented by an array of length 4 cq 2 front queue 0 1 2 3 The queue is now full. How can you tell? 2 rear 4 count 6-46

ADD ANOTHER ITEM! NEED TO EXPAND CAPACITY 0 1 2 3 2 cq front 2 rear queue 4 count We can t just double the size of the array: circular properties of the queue will be lost 0 1 2 3 4 5 6 7 2 cq front queue 2 rear 4 count These locations should be in use 6-47

We could build the new array, and copy the queue elements into contiguous locations beginning at location front: 0 1 2 3 4 5 6 7 cq 2 front 6 rear queue 4 count 6-48

Better: copy the queue elements in order to the beginning of the new array 0 0 1 2 3 4 5 6 7 cq front 4 rear queue 4 count 6-49

New element is added at rear = (rear+1) % queue.length See expandcapacity() in CircularArrayQueue.java 0 0 1 2 3 4 5 6 7 cq front 5 rear queue 5 count 6-50

ANALYSIS OF QUEUE OPERATIONS The linked implementation of a queue does not suffer because of the need to operate on both ends of the queue (why not?) enqueue operation: O(1) for linked implementation O(n) for circular array implementation if need to expand capacity, O(1) otherwise What about the noncircular array implementation? 6-51

ANALYSIS OF QUEUE OPERATIONS dequeue operation: O(1) for linked implementation O(1) for circular array implementation O(n) for noncircular array implementation (why?) 6-52