ScaleFree

DS & A(Queue)

CHAPTER 14 |

In this chapter, our topic of discussion will be the "Queue" Data Structure. But, before we get started, I would recommend you to read the previous chapters on Data Structures & Algorithms (especially the chapters on Array List, Linked List, Array Stack, and Linked Stack), that is in case it's your first time visiting my blog.
Queue:
  • Just like Stacks, Queues also are a restricted version of List but with a few minor differences compared to Stack. The following are some of the notable characteristics of a Queue:
    • Data can only be inserted from the rear/back. Data insertion is referred to as ENQUEUE.
    • Data can only be deleted from the front. Data deletion is referred to as DEQUEUE.
    • Alternatively, ENQUEUE and DEQUEUE should always be executed on the opposite ends of the Queue.
  • A Queue follows the FIFO(First In First Out) principle.
  • The first and the last elements are referred to as FRONT and REAR respectively.


Visual Representation:
  • Array-Based Queue:
  • Pointer-Based(Linked) Queue:
Some Theory on Array Based Queue...

As mentioned above a Queue is a restricted version of List so all we need to do is modify the Array-Based list to get our Queue implementation, isn't it? Not actually, If we simply try to implement the Array-Based List to work as an Array-Based Queue the resulting implementation will be kinda inefficient. Why is that? Let's figure that out.

Consider, we have to store n items in a Queue. So, if we try to implement the Queue to work just like an Array-based list then we will need to store those n items in the first n positions of the array, i.e. (0 to n-1). And the Queue will look something like the following.
A Queue has two access points namely FRONT and REAR, we have something analogous to those in an Array List as well, remember HEAD and TAIL?
So, if we try to implement a Queue just like an Array List we would be left with the following two choices:
  • Case 1: (ENQUEUE - Rear Shifts Right)
  • Case 2: (DEQUEUE - Front Shifts Left)
As mentioned previously implementing a Queue in this manner will be inefficient, but why is it so? Everything feels right, Isn't it? Not actually. To find the issues we have to analyze the ENQUEUE and DEQUEUE operation in both cases.

Case 1 Analysis:

As we already know that ENQUEUE operation is executed from the REAR and DEQUEUE operation is executed from the FRONT. So it can be easily observed that an ENQUEUE operation will require O(1) time only as it is similar to the Append function of the List. But a DEQUEUE operation will require O(n) time, as we will need to shift the remaining n-1 items to the left after removing the element at the FRONT.

Case 2 Analysis:

In Case 2, an ENQUEUE operation will require O(1) time whereas a DEQUEUE operation will require O(n) time, as we will need to shift the pre-existing items to the right before inserting a new element at the REAR.

Solution:

Since both Case 1 and Case 2 are inefficient, we have to approach this problem in a slightly different way, unlike a normal Array-based list. So, we will be making the following changes for a more efficient implementation.
  1. Remove the restriction requiring the queue items to be placed in the first n position of the array. So, the items of the queue can exist anywhere in the array as long as all the items exist in contiguous array positions.
  2. The REAR and FRONT will be arranged as the following. 
  1. FRONT and REAR will shift right on DEQUEUE and ENQUEUE respectively and that also in just O(1) time. This implementation will also let us know that the array is empty when REAR<FRONT.


Queue ADT:

  1. //Queue.h

  2. template<typename e> class Queue
  3. {
  4.      public:
  5.      virtual bool enqueue() = 0;
  6.      virtual bool dequeue() = 0;
  7.      virtual void print() const = 0;
  8. }

Queue Implementation:
  • Array Based Queue Implementation
  1. //AQueue.h

  2. #include"Queue.h"
  3. template<typename e> class AQueue:public Queue<e>
  4. {
  5.     int maxSize;
  6.     int front;
  7.     int rear;
  8.     e* queueArray;
  9. public:
  10.     AQueue(int sizeValue = 0)
  11.     {
  12.         maxSize = sizeValue;
  13.         rear = 0;
  14.         front = 1;
  15.         queueArray = new e[maxSize];
  16.     }
  17.     ~AQueue ()
  18.     {
  19.         delete [] queueArray;
  20.     }

  21.     int queueLength()
  22.     {
  23.         return (rear-front)+1;
  24.     }

  25.     bool enqueue(const e&);
  26.     bool dequeue(e&);
  27.     void print() const;
  28. };

  29. template <typename e>
  30. bool AQueue<e>::enqueue(const e& item)
  31. {
  32.     if (rear == maxSize) return false;
  33.     queueArray[++rear] = item;
  34.     return true;
  35. }

  36. template <typename e>
  37. bool AQueue<e>::dequeue(e& item)
  38. {
  39.     if (queueLength() == 0) return false;
  40.     item = queueArray[front++];
  41.     return true;
  42. }

  43. template<typename e>
  44. void AQueue<e>::print() const
  45. {
  46.     int tempCounter = front;
  47.     std::cout<<"< ";
  48.     while(tempCounter <= rear)
  49.     {
  50.         std::cout<<queueArray[tempCounter]<<" ";
  51.         tempCounter++;
  52.     }
  53.     std::cout<<">";
  54. }
  • Linked Queue Implementation
  1. //Node.h

  2. template<typename e> class Node
  3. {
  4. public:
  5.     e element;
  6.     Node<e>* next;
  7.     Node(e elemVal = 0,Node<e>* nextVal = nullptr)
  8.     {
  9.         element = elemVal;
  10.         next = nextVal;
  11.     }
  12.     Node(Node<e>* nextVal = nullptr)
  13.     {
  14.         next = nextVal;
  15.     }
  16. };

  1. //LQueue.h

  2. #include"Queue.h"
  3. #include"Node.h"
  4. #include<iostream>

  5. template<typename e> class LQueue : public Queue<e>
  6. {
  7.     Node<e>* rear;
  8.     Node<e>* front;
  9.     int size;

  10. public:
  11.     LQueue()
  12.     {
  13.         rear = front = nullptr;
  14.         size = 0;
  15.     }

  16.     bool enqueue(const e&);
  17.     bool dequeue(e&);
  18.     void print() const;
  19.     void clear();

  20.     int length(){ return size;}
  21.     ~LQueue(){clear();}
  22. };

  23. template<typename e>
  24. bool LQueue<e>:: enqueue(const e& item)
  25. {
  26.     if(rear == nullptr)
  27.     {
  28.         front = rear = new Node<e>(item,nullptr);
  29.     }
  30.     else
  31.     {
  32.         rear->next = new Node<e>(item,nullptr);
  33.         rear = rear->next;
  34.     }
  35.     size++;
  36.     return true;
  37. }

  38. template<typename e>
  39. bool LQueue<e>:: dequeue(e& item)
  40. {
  41.     if(size == 0) return false;
  42.     item = front->element;
  43.     Node<e>* temp = front;
  44.     front = front->next;
  45.     delete temp;
  46.     if(front==nullptr) rear = nullptr; //if not done rear will be a dangling pointer
  47.     size--;
  48.     return true;
  49. }

  50. template<typename e>
  51. void LQueue<e>:: print() const
  52. {
  53.     Node<e>* temp = front;
  54.     std::cout<<"< ";
  55.     while(temp != rear->next)
  56.     {
  57.         std::cout<<temp->element<<" ";
  58.         temp = temp->next;
  59.     }
  60.     std::cout<<">";
  61.     delete temp;
  62. }

  63. template<typename e>
  64. void LQueue<e>:: clear()
  65. {
  66.     delete rear;
  67.     delete front;
  68. }


Testing the Queue implementation

  1. //main.cpp

  2. #include<iostream>
  3. #include"AQueue.h"               //Use this only for testing Array based Queue
  4. #include"AQueue.h"               //Use this only for testing Linked Queue
  5. using namespace std;

  6. int main()
  7. {
  8.     AQueue<int> newQueue(10);    //Use this only for testing Array based Queue
  9.     LQueue<int> newQueue;        //Use this only for testing Linked Queue
  10.     newQueue.enqueue(1);
  11.     newQueue.enqueue(2);
  12.     newQueue.enqueue(3);
  13.     newQueue.enqueue(4);
  14.     newQueue.enqueue(5);
  15.     newQueue.enqueue(6);
  16.     newQueue.enqueue(7);
  17.     newQueue.enqueue(8);
  18.     newQueue.enqueue(9);
  19.     newQueue.enqueue(0);
  20.     newQueue.print();

  21.     int dequeued_element;

  22.     int length = newQueue.length(); // initialize newQueue.length() because it's value 
  23.                                     // changes with every enqueue or dequeue
  24.     cout<<"\n\n";
  25.     for(int i = 0; i<length ; i++)
  26.     {
  27.         newQueue.dequeue(dequeued_element);
  28.         cout<<"Removed: "<<dequeued_element<<"\n";
  29.     }

  30.     return 0;
  31. }

Array-Based Queue Implementation: More Issues

If you guys thought that our implementation for the Array-based Queue above is perfect I would have to disappoint you guys cos it still has some daunting issues.

Let's say we have the following Queue and we executed several DEQUEUE operation on it:



After the first DEQUEUE


After the second DEQUEUE


After the third DEQUEUE

I am sure that by this point it's pretty clear that if we use the Array-Based Queue implementation mentioned above then the Queue will become unusable after several ENQUEUE & DEQUEUE operations. So, what's the solution to that problem. Any guess? Don't worry if you can't figure it out, the following section is all about the solution we are looking for.


Circular Queue (aka Circular/Ring Buffer) : The solution

As the name suggests it is a circular Queue Data Structure. But don't get fooled by the name, just because the name contains the term Circular it doesn't mean that the data structure itself is circular, but it's the implementation that makes it behave as if it's circular in nature. We will still be using an Array which is a Linear Data Structure. The following are some of the properties of a Circular Queue implementation.
  • FRONT and REAR keeps on getting incremented till it reaches the final index.
  • When FRONT is at the last index the next DEQUEUE will move the FRONT to its initial index again. Similarly, when REAR is at the last index the next ENQUEUE will move the REAR to its initial index again.
  • A starting empty array slot is necessary. So, a Queue that stores n elements will always require an array of size n+1.
Why do we need the empty array slot?

The empty slot is necessary because of the otherwise possible ambiguity that the circular Queue might encounter. Let's discuss it in detail, Consider the following two cases of circular Queue without an empty array slot.
  • Case 1: When the Queue is empty
  • Case 2: When the Queue is full


As you can see from Case 1 and Case 2 that if the empty array slot in the Queue implementation is not present then a full and an empty Queue cannot be distinguished leading to an ambiguous scenario. So, the empty array is mandatory in a Circular implementation.


Circular Queue Implementation:
I leave it to you guys as an exercise. Try implementing it. All the best...
OR
You can join our Facebook group for the code

( If you like the content here, follow TSP on social media to get notified on future updates)




Comments

Share on Social Media

Most Viewed Posts

DS & A (Algorithm Analysis - Best, Worst and Average Case)

SPACE & DRAGONS