Queues CSE, POSTECH 2 2 Queues Like a stack, special kind of linear list One end is called front Other end is called rear Additions (insertions or enqueue)

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Linear Lists – Array Representation
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Data Structures and Algorithms (60-254)
Queues Linear list. One end is called front. Other end is called rear. Additions are done at the rear only. Removals are made from the front only.
Queues Linear list. One end is called front. Other end is called rear. Additions are done at the rear only. Removals are made from the front only.
Queues CS-212 Dick Steflik. Queues First In, First Out operation – FIFO As items are added they are chronologically ordered, items are removed in their.
CHAPTER 7 Queues.
ADT Queue 1. What is a Queue? 2. STL Queue 3. Array Implementation of Queue 4. Linked List Implementation of Queue 5. Priority Queue.
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
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.
Data Structure Dr. Mohamed Khafagy.
Queue Chapter 9 Stacks Last in first out (LIFO)Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Queue RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
CS Data Structures II Review COSC 2006 April 14, 2017
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 The Stack ADT (§4.2) The Stack ADT stores arbitrary objects Insertions and deletions.
© 2006 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 Queues CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
Queues.
Stacks CSE, POSTECH. 2 2 Stacks Linear list One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Priority Queues, Heaps & Leftist Trees
ADT Stacks and Queues. Stack: Logical Level “An ordered group of homogeneous items or elements in which items are added and removed from only one end.”
Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Chapter 7 Queues. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 7-2 Chapter Objectives Examine queue processing Define a queue abstract.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 8 Stacks and Queues Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
© 2006 Pearson Addison-Wesley. All rights reserved8 A-1 Chapter 8 Queues (slightly modified by Dan Fleck)
Stacks and Linked Lists. Abstract Data Types (ADTs) An ADT is an abstraction of a data structure that specifies – Data stored – Operations on the data.
Linked Lists list elements are stored, in memory, in an arbitrary order explicit information (called a link) is used to go from one element to the next.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Queue 1 Operations on Queues A Dequeue Operation An Enqueue Operation Array Implementation Link list Implementation Examples.
1 Chapter 7 Stacks and Queues. 2 Stack ADT Recall that ADT is abstract data type, a set of data and a set of operations that act upon the data. In a stack,
A data structure is a type of data storage ….similar to an array. There are many data structures in Java (Stacks, Queues, LinkedList, Sets, Maps, HashTables,
Stacks Chapter 8. Objectives In this chapter, you will: Learn about stacks Examine various stack operations Learn how to implement a stack as an array.
Stack Overview. Stack Stack ADT Basic operations of stack – Pushing, popping etc. Implementations of stacks using – array – linked list.
Stacks And Queues Chapter 18.
1 Linked-list, stack and queue. 2 Outline Abstract Data Type (ADT)‏ Linked list Stack Queue.
Applications of Stacks and Queues Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Queues Linear list. One end is called front. Other end is called rear. Additions are done at the rear only. Removals are made from the front only. FIFO.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
Computer Science Department Data Structures and Algorithms Queues Lecture 5.
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.
1 Chapter 6 Queues. 2 Topics FIFO (first0in-first0out) structure Implementations: formula-based and linked classes Applications: –railroad-switching problem.
SNU IDB Lab. Ch10. Queues © copyright 2006 SNU IDB Lab.
© 2011 Pearson Addison-Wesley. All rights reserved 8 B-1 Chapter 8 (continued) Queues.
Data Structures. Abstract Data Type A collection of related data is known as an abstract data type (ADT) Data Structure = ADT + Collection of functions.
Welcome to CSCE 221 – Data Structures and Algorithms
COP 3530 Discussion Session #6 Yilin Shen. Outline Chapter 7 o Q35p 250 o Q39p 265 Chapter 8 o Problem 8.5.3: Rearranging Railroad carsp 289 o Problem.
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.
Data Structures David Kauchak cs302 Spring Data Structures What is a data structure? Way of storing data that facilitates particular operations.
1 Queues (Continued) Queue ADT Linked queue implementation Array queue implementation Circular array queue implementation Deque Reading L&C , 9.3.
Chapter 7 A Queues. © 2004 Pearson Addison-Wesley. All rights reserved7 A-2 The Abstract Data Type Queue A queue –New items enter at the back, or rear,
 In general, Queue is line of person waiting for their turn at some service counter like ticket window at cinema hall, at bus stand or at railway station.
1 Chapter 5 Stacks. 2 Topics LIFO (last-in-first-out) structure Implementations –Use class LinearList or Chain –from scratch Applications –parentheses.
© Oxford University Press All rights reserved. Data Structures Using C, 2e Reema Thareja.
1 Data Structures and Algorithms Queue. 2 The Queue ADT Introduction to the Queue data structure Designing a Queue class using dynamic arrays Linked Queues.
Review Array Array Elements Accessing array elements
Data Structures Using C, 2e
Queues.
CS505 Data Structures and Algorithms
COSC160: Data Structures: Lists and Queues
Lectures Queues Chapter 8 of textbook 1. Concepts of queue
Queues Queues Queues.
Queues.
Queues Linear list. One end is called front. Other end is called rear.
پشته ها و صف ها.
Queues Linear list. One end is called front. Other end is called rear.
Data Structures & Programming
Presentation transcript:

Queues CSE, POSTECH

2 2 Queues Like a stack, special kind of linear list One end is called front Other end is called rear Additions (insertions or enqueue) are done at the rear only Removals (deletions or dequeue) are made from the front only

3 Bus Stop Queue Bus Stop front rear Remove a person from the queue

4 Bus Stop Queue Bus Stop front rear

5 Bus Stop Queue Bus Stop front rear

6 Bus Stop Queue Bus Stop front rear Add a person to the queue A queue is a FIFO (First-In, First-Out) list.

7 7 Queue ADT AbstractDataType queue { instances ordered list of elements; one end is the front; the other is the rear; operations empty():Return true if queue is empty, return false otherwise size():Return the number of elements in the queue front():Return the front element of queue back():Return the back (rear) element of queue pop():Remove an element from the queue // dequeue push(x):Add element x to the queue // enqueue } It is also possible to represent Queues using 1. Array-based representation 2. Linked representation

8 The Abstract Class queue template // Program 9.1 class queue { public: virtual ~queue() {} virtual bool empty() const = 0; virtual int size() const = 0; virtual T& front() = 0; virtual T& back() = 0; virtual void pop() = 0; virtual void push(const T& theElement) = 0; };

9 9 Array-based Representation of Queue Using simple formula equation location(i) = i – 1 – The first element is in queue[0], the second element is in queue[1], and so on – Front always equals zero, back (rear) is the location of the last element, and the queue size is rear + 1 – How much time does it need for pop()?

10 Derive from ArrayLinearList When front is left end of list and rear is right end: – Queue.empty()  ArrayLinearList.empty() O(1) – x = Queue.front()  ArrayLinearList.get(0) O(1) – x = Queue.back()  ArrayLinearList.get(length)O(1) – Queue.push(x)  ArrayLinearList.insert(length, x)O(1) – Queue.pop()  ArrayLinearList.erase(0) O(length) To perform every operation in O(1) time, we need a customized array representation

11 Array-based Representation of Queue Using modified formula equation location(i) = location(1) + i - 1 – No need to shift the queue one position left each time an element is deleted from the queue – Instead, each deletion causes front to move right by 1 – Front = location(1), rear = location(last element), and empty queue has rear < front – What do we do when rear = Maxsize –1 and front > 0?

12 Array-based Representation of Queue Shifting a queue – To continue adding to the queue, we shift all elements to the left end of the queue – But shifting increases the worst-case add time from  (1) to  (n)  Need a better method! Shifting a Queue

13 Array-based Representation of Queue Remedy in modified formula equation that can provide the worst-case add and delete times in  (1): location(i) = (location(1) + i – 1) % Maxsize  This is called a Circular Queue

14 Custom Array Queue Use a 1D array queue Circular view of array

15 Custom Array Queue Possible configurations with three elements.

16 Custom Array Queue Use integer variables ‘front’ and ‘rear’. – ‘front’ is one position counter-clockwise from first element – ‘rear’ gives the position of last element rear front

17 Custom Array Queue Add an element – Move ‘rear’ one clockwise. – Then put an element into queue[rear].

18 Custom Array Queue Remove an element – Move front one clockwise. – Then extract from queue[front].

19 Custom Array Queue Moving clockwise – rear++; if (rear == queue.length) rear = 0; – rear = (rear + 1) % queue.length;

20 Custom Array Queue Empty that queue rear front rear front

21 Custom Array Queue Empty that queue rear front rear front

22 Custom Array Queue Empty that queue – When a series of removals causes the queue to become empty, front = rear. – When a queue is constructed, it is empty. – So initialize front = rear = 0.

23 Custom Array Queue A Full Tank Please rear front rear front

24 Custom Array Queue A Full Tank Please rear front rear front

25 Custom Array Queue A Full Tank Please – When a series of adds causes the queue to become full, front = rear. – So we cannot distinguish between a full queue and an empty queue. How to differentiate two cases: queue empty and queue full?

26 Custom Array Queue Remedies – Don’t let the queue get full  When the addition of an element will cause the queue to be full, increase array size – Define a boolean variable lastOperationIsAdd  Following each add operation set this variable to true.  Following each delete operation set this variable to false.  Queue is empty iff (front == rear) && !lastOpeartionIsAdd  Queue is full iff (front == rear) && lastOperationIsAdd

27 Custom Array Queue Remedies (cont’d) – Define a variable NumElements  Following each add operation, increment this variable  Following each delete operation, decrement this variable  Queue is empty iff (front == rear) && (!NumElements)  Queue is full iff (front == rear) && (NumElements) See Programs 9.2, 9.3, 9.4 See Figure 9.7 for doubling array queue length

28 Linked Representation of Queue Can represent a queue using a chain Need two variables, front and rear, to keep track of the two ends of a queue Two options: 1) assign head as front and tail as rear (see Fig 9.8 (a)), or 2) assign head as rear and tail as front (see Fig 9.8 (b)) Which option is better and why?  See Figures 9.9 and 9.10

29 Linked Queue Representations Figure 9.8 Linked Queues HeadTail Head Tail

30 Add to & Delete from a Linked Queue What is the time complexity for Fig 9.8 (a)?  Θ(1) What is the time complexity for Fig 9.8 (b)?  Θ(1) What is the time complexity for Fig 9.9 (a)?  Θ(1) What is the time complexity for Fig 9.9 (b)?  Θ(n) So, which option is better?  Option 1

31 Linked Representation of Queue How can we implement a linked representation of queue? See Program 9.5 for implementing the push and pop methods of linkedQueue

32 Derive From ExtendedChain When front is left end of list and rear is right end: – empty()  extendedChain::empty() – size()  extendedChain::size() – front()  get (0) – back()  getLast() … new method – push(theElement)  push_back(theElement) – pop()  erase(0) abcde NULL firstNode lastNode frontrear

33 Revisit of Stack Applications Applications in which the stack cannot be replaced with a queue – Parentheses matching – Towers of Hanoi – Switchbox routing – Method invocation and return Application in which the stack may be replaced with a queue – Railroad Car Rearrangement – Rat in a maze

34 Application: Rearranging Railroad Cars Similar to problem of Section using stacks This time holding tracks lie between the input and output tracks with the following same conditions: – Moving a car from a holding track to the input track or from the output track to a holding track is forbidden These tracks operate in a FIFO manner  can implement using queues We reserve track Hk for moving cars from the input track to the output track. So the number of tracks available to hold cars is k-1.

35 Rearranging Railroad Cars When a car is to be moved to a holding track, use the following selection method: – Move a car c to a holding track that contains only cars with a smaller label – If multiple such tracks exist, select one with the largest label at its left end – Otherwise, select an empty track (if one remains) What happens if no feasible holding track exists?  rearranging railroad cars is NOT possible See Figure 9.11 and read its description

36 Implementing Rearranging Railroad Cars What should be changed in previous program (in Section 8.5.3)? 1. Decrease the number of tracks (k) by 1 2. Change the type of track to arrayQueue What is the time complexity of rearrangement?  O(numberOfCars * k) See Programs 9.6 and 9.7

37 Application: Wire Routing Similar to Rat in a Maze problem in Section 8.5.6, but this time it has to find the shortest path between two points to minimize signal delay Used in designing electrical circuit boards Read the problem description on pg. 336 Figure 9.12 Wire Routing Example

38 Wire Routing Algorithm The shortest path between grid positions a and b is found in two passes 1. Distance-labeling pass (i.e., labeling grids) 2. Path-identification pass (i.e., finding the shortest path)

39 Wire Routing Algorithm 1. Labeling Grids: Starting from position a, label its reachable neighbors 1. Next, the reachable neighbors of squares labeled 1 are labeled 2. This labeling process continues until we either reach b or have no more reachable squares. The shaded squares are blocked squares. Figure 9.13 Wire Routing

40 Wire Routing Algorithm 2. Finding the shortest path: Starting from position b, move to any one of its neighbors labeled one less than b’s label. Such a neighbor must exist as each grid’s label is one more than that of at least one of its neighbors. From here, we move to one of its neighbors whose label is one less, and so on until we reach a. Figure 9.13 Wire Routing

41 Wire Routing Algorithm Exercise Consider the wire-routing grid of Figure 9.13(a). You are to route a wire between a=(1, 1) and b=(1, 6). Label all grid positions that are reached in the distance-labeling pass by their distance value. Then use the methodology of the path-identification pass to mark the shortest wire path. ab a1b ab Is there only one shortest path?

42 Implementing Wire Routing Algorithm An m x m grid is represented as a 2-D array with a 0 representing an open position and a 1 representing a blocked position the grid is surrounded by a wall of 1s the array offsets helps us move from a position to its neighbors A queue keeps track of labeled grid positions whose neighbors have yet to be labeled What is the time complexity of the algorithm?  O(m 2 ) for labeling grids & O(length of the shortest path) for path construction Read Program 9.8

43 Application: Image-Component Labeling Background information: – A digitized image is an m x m matrix of pixels. – In a binary image, each pixel is 0 or 1. – A 0 pixel represents image background, while a 1 represents a point on an image component. – Two pixels are adjacent if one is to the left, above, right, or below the other. – Two component pixels that are adjacent are pixels of the same image component. Problem: Label the component pixels so two pixels get the same label iff they are pixels of the same image component.

44 Image-Component Labeling Example The blank squares represent background pixels and 1s represent component pixels Pixels (1,3), (2,3), and (2,4) are from the same component Figure 9.14 Image-Component Labeling

45 Image-Component Labeling Algorithm Idea:Similar to the wire-routing problem Steps: 1. Scan pixels one by one (row-major search). 2. When encounter a 1 pixel, give a unique component identifier. 3. Find all neighbors by expanding from that pixel and give the unique identifier. 4. Repeat for all pixels. See program 9.9 What is the time complexity of Program 9.9?

46 READING Read Machine Shop Simulation Read all of Chapter 9