The Queue ADT.

Slides:



Advertisements
Similar presentations
Data Structures Lecture 13: QUEUES Azhar Maqsood NUST Institute of Information Technology (NIIT)
Advertisements

COSC 1P03 Data Structures and Abstraction 9.1 The Queue Whenever you are asked if you can do a job, tell 'em, "Certainly, I can!" Then get busy and find.
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.
1 Queues (Continued) Applications for a queue Linked queue implementation Array queue implementation Circular array queue implementation Reading L&C 3.
queues1 Queues Data structures that wait their turn.
Topic 9 The Queue ADT.
CHAPTER 7 Queues.
5/4/20151 Queues Implementations. 5/4/20152 Outline Queues Basic operations Examples of useImplementations Array-based and linked list-based.
Chapter 7 Queues. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine queue processing Define a queue abstract.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
1 Queues Queue Concept Queue Design Considerations Queues in Java Collections APIs Queue Applications Reading L&C , 9.3.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
Chapter 7 Queues. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Chapter Objectives Examine queue processing Define a queue abstract.
Topic 3 The Stack ADT.
Chapter 3 Introduction to Collections – Stacks Modified
TK1924 Program Design & Problem Solving Session 2011/2012 L6: Queues.
1 CS 132 Spring 2008 Chapter 8 Queues. 2 Queue A data structure in which the elements are added at one end, called the rear, and deleted from the other.
COS 312 DAY 20 Tony Gauvin. Ch 1 -2 Agenda Questions? Capstone Progress reports over due Assignment 6 Posted – Due April 16 – Questions? Queues.
Data Structures Using Java1 Chapter 7 Queues. Data Structures Using Java2 Chapter Objectives Learn about queues Examine various queue operations Learn.
Lecture7: Queue Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Chapter 7 Queues Introduction Queue applications Implementations.
M180: Data Structures & Algorithms in Java Queues Arab Open University 1.
Copyright © Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Stack: a Linked Implementation
Elementary Data Structures
Review Array Array Elements Accessing array elements
The List ADT.
Data Structures Using C++ 2E
Using Queues: Coded Messages
Queues Rem Collier Room A1.02
Queues Implementations 6/17/2018.
Csc 2720 Data structure Instructor: Zhuojun Duan
COS 312 DAY 21 Tony Gauvin.
CSE 373: Data Structures and Algorithms
Queues Queue Concept Queue Design Considerations
Lectures Queues Chapter 8 of textbook 1. Concepts of queue
Queue.
Stacks and Queues.
Queues Queues Queues.
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Queues Chapter 8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Chapter 5 Queues.
Prof. Neary Adapted from slides by Dr. Katherine Gibson
CMSC 341 Lecture 5 Stacks, Queues
Queue, Deque, and Priority Queue Implementations
Queue, Deque, and Priority Queue Implementations
Stacks, Queues, and Deques
Queues.
Stacks and Queues.
Queues 11/22/2018 6:47 AM 5.2 Queues Queues Dr Zeinab Eid.
Stacks, Queues, and Deques
Cs212: Data Structures Computer Science Department Lecture 7: Queues.
CS210- Lecture 5 Jun 9, 2005 Agenda Queues
ADT Queue (Array Implementation)
More Data Structures (Part 1)
Using a Queue Chapter 8 introduces the queue data type.
Using a Queue Chapter 8 introduces the queue data type.
Stacks, Queues, and Deques
CSCS-200 Data Structure and Algorithms
Getting queues right … finally (?)
Stacks and Queues.
CHAPTER 3: Collections—Stacks
Presentation transcript:

The Queue ADT

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

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

Conceptual View of a Queue Adding an element Front of queue New element is added to the rear of the queue

Conceptual View of a Queue Removing an element New front element of queue Element is removed from the front of the queue

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)

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? Ticket counter simulation

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!

Operations on a Queue Operation Description dequeue enqueue first Removes an element from the front of the queue enqueue Adds an element to the rear of the queue first Examines the element at the front of the queue isEmpty Determines whether the queue is empty size Determines the number of elements in the queue toString Returns a string representation of the queue

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( ); }

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!

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)

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

An Encoded Message Using a Repeated Key v a g j h l m u r x 3 1 7 4 2 5 k w e d i s p Key Decoded message

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

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?

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

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 Average time (in seconds)

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

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

Linked Implementation of a Queue A queue q containing four elements rear q front 4 count

Discussion What if the queue is empty? What if there is only 1 element? queue is empty: count =0, front=rear=null only 1 element: front = rear

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 rear q front 5 count

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. rear q front 4 count

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

The LinkedQueue class { /** * Attributes */ private int count; 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

The enqueue( ) operation //----------------------------------------------------------------- // 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

The dequeue( ) operation //----------------------------------------------------------------- // 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--; rear = null; return result; } The dequeue( ) operation

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?

An Array Implementation of a Queue A queue aq containing four elements front 1 2 3 4 … queue aq 4 rear

Queue After Adding an Element Element is added at the array location given by the (old) value of rear, and then rear is incremented. 1 2 3 4 … queue aq 5 rear

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. 1 2 3 4 … queue aq 4 rear

Java Array Implementation See ArrayQueue.java

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

The enqueue( ) operation //----------------------------------------------------------------- // 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

The dequeue( ) operation //----------------------------------------------------------------- // 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

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

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

Circular Array Implementation of a Queue 3 2 3 4 1 front queue 5 cq 8 5 6 n-1 rear count n-2 7 n-3 8 . 9 . 10 .

A Queue Straddling the End of a Circular Array 98 2 3 4 1 front queue 5 cq 2 4 6 99 rear count 98 7 97 8 . 9 . 10 .

Circular Queue Drawn Linearly Queue from previous slide 98 cq front queue 1 2 3 4 96 97 98 99 … 2 4 rear count

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? Yes, so it may need enlarging

Example: array of length 4 What happens? 1 2 3 2 front queue cq Suppose we try to add one more item to a queue implemented by an array of length 4 1 3 rear count 1 2 3 The queue is now full. How can you tell? 2 front queue cq 2 4 rear count

Add another item! Need to expand capacity… 1 2 3 We can’t just double the size of the array and copy values to the same positions as before: circular properties of the queue will be lost 2 front queue cq 2 4 rear count 1 2 3 4 5 6 7 2 front queue cq 2 4 These locations should be in use rear count

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

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

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

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? O(1) if array is not full, O(n) if array is full and need to expand its capacity

Analysis of Queue Operations dequeue operation: O(1) for linked implementation O(1) for circular array implementation O(n) for noncircular array implementation (why?) O(1) if array is not full, O(n) if array is full and need to expand its capacity