DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

How to implement own circular queue in C++

C++ Implementation of Circular queue:

Implementation of Circular queue can be done in many ways but I have implemented using array and size is given by user with template using C++.

Source code:

/*
Program:Circular Queue 
Author: Alpha Master
Date: 27 Nov 2021
*/

//Header File
#include<iostream>

template<class T>
class CircularQueue
{
	int mSz;
	int mFront;
	int mRear;
	T* mArray;
	public:
	CircularQueue(int sz);
	~CircularQueue();
	void push(T val);
	T top();
	void pop();
	bool isEmpty();
};

template<class T>
CircularQueue<T>::CircularQueue(int size):mSz(size)
{
	mArray = new T[size];
	mFront = mRear = -1;
}

template<class T>
CircularQueue<T>::~CircularQueue()
{
	if(mArray != nullptr)
	{
		delete[] mArray;
		mArray = nullptr;
	}
	mFront = mRear = -1;
}

template<class T>
void CircularQueue<T>::push(T val)
{
	//if its full
	if((mRear == mSz -1 && mFront == 0) || (mRear+1 == mFront ))
	{
		std::cout<<"Queue is full"<<std::endl;
		return;
	}

	//move mRear
	if(mRear == mSz-1)
	mRear = 0;
	else
	mRear++;
	
	//insert the data
	mArray[mRear] = val;

        //if its first element
	if(mFront == -1)
	mFront = 0;

	return;
}

template<class T>
bool CircularQueue<T>::isEmpty()
{
	if(mFront == -1)
	return true;
	else
	return false;
}

template<class T>
T CircularQueue<T>::top()
{
	return mArray[mFront];
}

template<class T>
void CircularQueue<T>::pop()
{
	//if no data is present
	if(mFront == -1)
	{
	std::cout<<"Queue is empty"<<std::endl;
	}

	//if only one element
	if(mFront == mRear)
	{
		mFront = mRear = -1;
	}
	else
	{
		//if Front is pointing to last element
		if(mFront == mSz -1)
		mFront = 0;
		else
		mFront++;
	
	}
	return;
}

int main()
{
	std::cout<<"Circular Queue"<<std::endl;
        CircularQueue<int> obj(5);
        obj.push(1);
        obj.push(2);
        obj.push(3);
        obj.push(4);
        obj.push(5);
        obj.push(6);
	//remove the first four element
	obj.pop();
        obj.pop();
        obj.pop();
        obj.pop();

        obj.push(6);
        obj.push(7);
        obj.push(8);
        obj.push(9);

        while(!(obj.isEmpty()))
        {
                std::cout<<obj.top()<<" ";
                obj.pop();
        }
        std::cout<<" "<<std::endl;
	return 0;
}

Output:

Circular Queue
Queue is full
5 6 7 8 9 

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer