implement queue using linked list in c++

C++ program for implement queue using linked list. Here problem description and explanation.

// Include header file
#include <iostream>
using namespace std;
/*
  C++ Program for
  Implement queue using linked list
*/
// Create Q node
class QNode
{
	public: 
    int data;
	QNode *next;
	QNode(int value)
	{
		this->data = value;
		this->next = nullptr;
	}
};
class MyQueue
{
	public: 
    QNode *head;
	QNode *tail;
	int count;
	MyQueue()
	{
		this->head = nullptr;
		this->tail = nullptr;
		this->count = 0;
	}
	int size()
	{
		return this->count;
	}
	bool isEmpty()
	{
		return this->count == 0;
	}
	// Add new node of queue
	void enqueue(int value)
	{
		// Create a new node
		QNode *node = new QNode(value);
		if (this->head == nullptr)
		{
			// Add first element into queue
			this->head = node;
		}
		else
		{
			// Add node at the end using tail 
			this->tail->next = node;
		}
		this->count++;
		this->tail = node;
	}
	// Delete a element into queue
	int dequeue()
	{
		if (this->head == nullptr)
		{
			cout << "Empty Queue" << endl;
			return -1;
		}
		// Pointer variable which are storing 
		// the address of deleted node
		QNode *temp = this->head;
		// Visit next node 
		this->head = this->head->next;
		this->count--;
		if (this->head == nullptr)
		{
			// When deleting a last node of linked list
			this->tail = nullptr;
		}
		return temp->data;
	}
	// Get front node
	int peek()
	{
		if (this->head == nullptr)
		{
			cout << "Empty Queue" << endl;
			return -1;
		}
		return this->head->data;
	}
};
int main()
{
	MyQueue *task = new MyQueue();
	// Initially number of element
	cout << "isEmpty : " << task->isEmpty() << endl;
	// Add element into queue
	task->enqueue(10);
	task->enqueue(20);
	task->enqueue(30);
	task->enqueue(40);
	task->enqueue(50);
	// Test other function
	cout << "size : " << task->size() << endl;
	cout << "peek : " << task->peek() << endl;
	cout << "dequeue : " << task->dequeue() << endl;
	cout << "size : " << task->size() << endl;
	cout << "peek : " << task->peek() << endl;
	cout << "isEmpty : " << task->isEmpty() << endl;
	return 0;
}

Output

isEmpty : 1
size : 5
peek : 10
dequeue : 10
size : 4
peek : 20
isEmpty : 0


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved