Queues Adt
Queues Adt
Queues
• Definition of a Queue
• Examples of Queues
• Design of a Queue Class
• Different Implementations of the
Queue Class
Introduction to Queues
• A queue is a waiting line
Front
Rear
The Queue Operations
Front
Rear
The Queue Operations
Front
Rear
Queue Abstract Data Type
• Basic operations
– Construct a queue
– Check if empty
– Enqueue (add element to back)
– Front (retrieve value of element from front)
– Dequeue (remove element from front)
A Graphic Model of a Queue
Head:
Tail:
All items are
All new items
deleted from
are added on this end
this end
Operations on Queues
• Insert(item): (also called enqueue)
– It adds a new item to the tail of the queue
• Remove( ): (also called delete or dequeue)
– It deletes the head item of the queue, and returns to the caller. If the queue is
already empty, this operation returns NULL
• getHead( ):
– Returns the value in the head element of the queue
• getTail( ):
– Returns the value in the tail element of the queue
• isEmpty( )
– Returns true if the queue has no items
• size( )
– Returns the number of items in the queue
Queue as a Class
• Much like stacks and linked lists were
designed and implemented as classes, a
queue can be conveniently packaged as a class
• It seems natural to think of a queue as similar
to a linked list, but with more basic
operations, to enforce the FIFO order of
insertion and deletion
Designing and Building a Queue Class
Array-Based
• Consider an array in which to store a
queue
Enqueue(70)
Queue Operation
• Enqueue(80)
• Enqueue(50)
Queue Operation
• Dequeue()
• Dequeue()
Queue Operation
• Enqueue(90)
• Enqueue(60)
Circular Queue
• Problems
– We quickly "walk off the end" of the array
• Possible solutions
– Shift array elements
– Use a circular queue
4 8 6
An array of integers
to implement a We don't care what's in
queue of integers this part of the array.
Array Implementation
4 8 6
A Dequeue Operation
2 last
4 8 6
An Enqueue Operation
3 last
8 6 2
At the End of the Array
2 6 1
At the End of the Array
0 last
4 2 6 1
Array Implementation
4 8 6
Linked List Implementation
15
10
7
null
head_ptr
tail_ptr
Linked List Implementation
15
10
7
null
head_ptr
tail_ptr
Linked List Implementation
10
7
null
head_ptr
tail_ptr
Rear
Abstract Data Type
• Abstract Data Type as a design tool
• Concerns only on the important concept or
model
• No concern on implementation details.
• Stack & Queue is an example of ADT
• An array is not ADT.
What is the difference?
• Stack & Queue vs. Array
– Arrays are data storage structures while stacks and queues
are specialized DS and used as programmer’s tools.
• Stack – a container that allows push and pop
• Queue -‐‐ a container that allows enqueue and
dequeue
• No concern on implementation details.
• In an array any item can be accessed, while in these
data structures access is restricted.
• They are more abstract than arrays.
Questions?
• Array is not ADT
• Is Linked list ADT?