CH 4 - Queues - New
CH 4 - Queues - New
S
Queues – An Overview
Queues:
◦ Like stacks, Queues are an Abstract Data Type
◦ They are NOT built-in
◦ We must define them and their behaviours
◦ So what is a queue?
◦ A data structure that stores information in the form of a typical waiting line
◦ New items are added at the end of the queue
◦ Elements are removed from the front of the queue
◦ So unlike a stack
◦ A queue is accessible from both ends (front and end)
Queues
Access Policy:
◦ The first element that is inserted into the queue is the
first element that will leave the queue
◦ Therefore, in order for the last element to leave the queue, it must wait
until all elements preceding it are removed
◦ Known as the “First in, First out” access policy
◦ FIFO for short
◦ Real life example: waiting in line to be served
◦ When a customer arrives, they enter the line at the back
◦ They wait their turn
◦ Finally, they get to the front, are served, and exit the line
Queues
Basic Operations:
◦ enqueue:
◦ Inserts the element at the rear of the queue
◦ O(1) time
◦ dequeue:
◦ Removes the element at the front of the queue
◦ O(1) time
◦ peek:
◦ Looks at the element at the front of the queue without actually removing it
◦ O(1) time
Queues
Basic Operations:
◦ isEmpty:
◦ Checks to see if the queue is empty
◦ O(1) time
◦ isFull:
◦ Checks to see if the queue is full
◦ O(1) time
◦ clear:
◦ Clears the contents of the queue
◦ In “queue” order
◦ From front to back
◦ O(n) time
FIFO Nature of a Queue
Queues: Array
Implementation
Array Implementation:
◦ How would you implement a queue using an array?
◦ Think of what “stuff” you would need...
◦ Other than the actual array, what else do you need?
◦ Remember, you need to enqueue and dequeue
◦ Meaning:
◦ You need to ALWAYS know where the front and back of the queue are
brute-force method
Queues: Array
Implementation
Queues: Array
Implementation
Queues: Array
Implementation
What is wrong with the last example?
◦ enqueues run in O(1) time.
◦ This is a GOOD thing!
◦ But look at the dequeue
◦ How long does a dequeue take?
◦ The dequeue itself takes O(1) time
◦ However, after the first node is removed, ALL nodes, that remain in the
queue after the dequeue , must be moved forward one position in the
array
◦ Possibly n elements have to move after one dequeue
◦ This is O(n) time per deletion!
◦ And we know, conceptually, a dequeue should be O(1)
Queues: Circular Array Implementation
Circular arrays are a very common way of implementing an
array - based queue.
What is a circular array?
◦ It is a regular array
◦ We simply “view” it as being circular