C++ data structure implementation of the circular sequence queue

  • 2020-05-12 02:54:29
  • OfStack

Data structure and C++ are used to implement the circular sequential queue

Operation characteristics of queues: first in, first out The elements in the queue have the same type Adjacent elements have a precursor and successor relationship Set two Pointers, the head and the tail, to improve the time performance of the outgoing team

Convention: the team head pointer front points to the first position of the team head element, and the team tail pointer rear points to the team tail element

To solve the false overflow, we created a circular queue by connecting the first and last of the array of the storage queue.

How to tell if the circle is empty?

Empty: front = rear

How do I stack a circular queue?

Team: full front = rear

So the problem is, the condition of the queue empty and the condition of the queue full are the same, in order to avoid the condition of the queue empty when the queue is full or vice versa, we need to modify the condition of the queue full to separate the queue empty from the condition of the queue full.
Method: 1 element space is wasted, and the array has only 1 free cell when the queue is full. Full team conditions :(rear+1)%QueueSize==front

Here is the implementation code:

File CirQueue h


#ifndef CirQueue_byNim
#define CirQueue_byNim

#include<iostream>
using namespace std;

const int QueueSize=100;  // Maximum storage space for a circular queue  
template <class T>
class CirQueue
{
  private:
    T *data;  // An array that stores data  
    int front,rear; // Head and tail pointer  
  public:
    CirQueue()
    {
      data=new T[QueueSize];
      front=rear=0;
    }
    ~CirQueue()
    {
      delete []data;
      front=rear=0;
    }
    void EnQueue(T e)
    {
      if((rear+1)%QueueSize==front)  // Team full conditions  
        throw " The overflow ";
      rear=(rear+1)%QueueSize;
      data[rear]=e;
    }
    T DeQueue()
    {
      if(rear==front)// Team air condition  
        throw " underflow ";
      front=(front+1)%QueueSize;
      return data[front];
    }
    T GetQueue()
    {
      if(rear==front)// Team air condition  
        throw " underflow ";
      return data[(front+1)%QueueSize];
    }
    bool empty()
    {
      if(front==rear) // Conditions of queue vacancy: front==rear 
        return true;
      return false;
    }
};

#endif

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: