Answer to Question #304691 in C++ for Olivia

Question #304691

Task:


Your task is to make 2 circular queues using static array of same size. User should be allowed to input values at the back of the queue. And when an element in removed from the first queue by moving front pointer it should be instered into the second circular queue and you should keep checking both the circular queues if they are full or have they been emptied.

1
Expert's answer
2022-03-02T01:17:00-0500
#include<bits/stdc++.h>
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();
};

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) /* Insert First Element */
	{
		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();
	printf("\nDeleted value = %d", q.deQueue());
	printf("\nDeleted value = %d", q.deQueue());
	q.displayQueue();
	q.enQueue(9);
	q.enQueue(20);
	q.enQueue(5);
	q.displayQueue();
	q.enQueue(20);
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog