DigestCPP

Lets Understand With Example

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

How to implement own queue in C++

C++ implementation of own queue:

Implementation of queue can be done in many ways but I have implemented using Linked list with template using C++.

Source code of queue:

/*
Program:Queue with link list 
Author: Alpha Master
Date: 27 Nov 2021
*/

//Header File
#include<iostream>

template<class T>
class Queue
{
	struct node
	{
		T data;
		node* next;
	} * mFront, *mRear;
	public:
	Queue(){mFront = mRear = nullptr; }
	~Queue();	
	bool isEmpty();
	void push(T val);
	T top();
	void pop();
};

template<class T>
Queue<T>::~Queue()
{
	if(mFront == nullptr)
	return;

	//iterate
	node* tmp = nullptr;
	while(mFront != nullptr)
	{
		tmp = mFront;
		mFront = mFront->next;
		delete tmp;
	}
	
}

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

template<class T>
void Queue<T>::push(T val)
{
	node* tmp = new node;
	if(tmp == nullptr)
	{
	std::cout<<"Queue is full"<<std::endl;
	return;
	}
	tmp->data = val;
	tmp->next = nullptr;
	//if first push
	if(mFront == nullptr)
	{
		mFront = mRear = tmp;
	}
	else
	{
		mRear->next = tmp;
		mRear = mRear->next;
	}
	return;
}

template<class T>
T Queue<T>::top()
{
	return(mFront->data);
}

template<class T>
void Queue<T>::pop()
{
	if(mFront == nullptr)
	return;

	node* tmp = mFront;
	mFront = mFront->next;
	delete tmp;
}

int main()
{
	std::cout<<"Queue implemented using linked list"<<std::endl;
        Queue<int> obj;
        obj.push(1);
        obj.push(2);
        obj.push(3);
        obj.push(4);
        obj.push(5);
 
        while(!(obj.isEmpty()))
        {
                std::cout<<obj.top()<<" ";
                obj.pop();
        }
        std::cout<<" "<<std::endl;
 
        //queue with float
        Queue<float>obj1;
        obj1.push(6.3);
        obj1.push(7.3);
        obj1.push(8.2);
        obj1.push(9.1);
        obj1.push(10.5);
 
        while(!(obj1.isEmpty()))
        {
                std::cout<<obj1.top()<<" ";
                obj1.pop();
        }
        std::cout<<" "<<std::endl;
 
 
        std::cout<<"Bye"<<std::endl;
	return 0;
}

Output:

Queue implemented using linked list
1 2 3 4 5  
6.3 7.3 8.2 9.1 10.5  
Bye

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer