Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Array implementation of Queue using class in c++

#include<iostream>
using namespace std;
#define n 101

class Queue
{
public:
	Queue()
	{
		rear = -1;
		front = -1;
	}
	bool IsEmpty()
	{
		if (rear == -1 && front == -1)
			return true;
		return false;
	}
	bool IsFull()
	{
		if ((rear + 1) % n == front)
			return true;
		return false;
	}
	void EnQueue(int x)
	{
		if (IsFull())
		{
			cout << "Queue is full!
";
			return;
		}
		else if (IsEmpty())
		{
			rear = front = 0;
		}
		else
		{
			rear = (rear + 1) % n;
		}
		Array[rear] = x;
	}
	void Dequeue()
	{
		if (IsEmpty())
		{
			cout << "Queue is Empty!
";
			return;
		}
		else if (rear == front)
		{
			rear = front = -1;
		}
		else
		{
			front = (front + 1) % n;
		}
	}
	int Front()
	{
		if (front == -1)
		{
			cout << "Queue is Empty!
";
			return -1;
		}
		return Array[front];
	}
	void print()
	{
		int cnt = (rear + n - front) % n + 1;
		cout << "Queue: ";
		for (int i = 0; i < cnt; i++)
		{
			int idx = (front + i) % n;
			cout << Array[idx] << " ";
		}
		cout << "

";
	}
private:
	int Array[n];
	int rear;
	int front;
};

int main()
{
	Queue q;

	//insert
	q.EnQueue(1);
	q.EnQueue(2);
	q.EnQueue(3);
	q.EnQueue(4);
	q.EnQueue(5);

	//print
	q.print();      //should print 1 2 3 4 5 

	//delete
	q.Dequeue();    //should delete 1
	q.Dequeue();    //should delete 2

	//print
	q.print();     //should print 3 4 5

	//get feont 
	cout << q.Front() << "
";   //should print 3

	return 0;
}
Source by www.codegrepper.com #
 
PREVIOUS NEXT
Tagged: #Array #implementation #Queue #class
ADD COMMENT
Topic
Name
9+6 =