Make an array based circular queue
Make a function as follows
bool search(int key)
This function searches if element exists in circular queue or not
Requirements :
Test run in main
No global decelerations
#include <iostream>
using namespace std;
class Queue
{
int rear, front;
int size;
int* arr;
public:
Queue(int s)
{
front = rear = -1;
size = s;
arr = new int[s];
}
void enQueue(int value);
int deQueue();
void displayQueue();
bool search(int key);
};
bool Queue::search(int key)
{
for (int i = 0; i < size; i++)
{
if (arr[i] == key)
{
return 1;
}
}
return 0;
}
void Queue::enQueue(int value)
{
if ((front == 0 && rear == size - 1) ||
(rear == (front - 1) % (size - 1)))
{
printf("\nQueue is Full");
return;
}
else if (front == -1)
{
front = rear = 0;
arr[rear] = value;
}
else if (rear == size - 1 && front != 0)
{
rear = 0;
arr[rear] = value;
}
else
{
rear++;
arr[rear] = value;
}
}
int Queue::deQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return INT_MIN;
}
int data = arr[front];
arr[front] = -1;
if (front == rear)
{
front = -1;
rear = -1;
}
else if (front == size - 1)
front = 0;
else
front++;
return data;
}
void Queue::displayQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return;
}
printf("\nElements in Circular Queue are: ");
if (rear >= front)
{
for (int i = front; i <= rear; i++)
printf("%d ", arr[i]);
}
else
{
for (int i = front; i < size; i++)
printf("%d ", arr[i]);
for (int i = 0; i <= rear; i++)
printf("%d ", arr[i]);
}
}
int main()
{
Queue q(5);
q.enQueue(14);
q.enQueue(22);
q.enQueue(13);
q.enQueue(-6);
q.displayQueue();
int value = 0;
std::cout << "\nEnter value to search : ";
std::cin >> value;
if (q.search(value))
{
std::cout << "There is such value\n";
}
else
{
std::cout << "There is no such value\n";
}
system("pause");
return 0;
}
Comments
Leave a comment