In: Computer Science
Task 1: [10 Marks] Write a function “reverse” in your queue
class (linked list implementation) that
reverses the whole queue.
In your driver file (main.cpp), create an integer queue, push some
values in it, call the reverse
function to reverse the queue and then print the queue.
Queue work in order is First In First Out (FIFO) with front and rear. In simple queue with linked list reverse implementation is not possible so you have to use the D-queue with Linklist. In this program I implement the reverse by simple storing value in array and print in reverse.
Write a
function “reverse” in your queue class (linked list implementation)
that
reverses the whole queue.
#include <iostream>
using namespace std;
struct node {
int data;
struct node *next;
};
struct node* front_1 = NULL;
struct node* rear_1 = NULL;
struct node* temp;
void Insert() {
int val;
cout<<"Insert the element in the queue : "<<endl;
cin>>val;
if (rear_1 == NULL) {
rear_1 = (struct node *)malloc(sizeof(struct node));
rear_1->next = NULL;
rear_1->data = val;
front_1 = rear_1;
} else {
temp=(struct node *)malloc(sizeof(struct node));
rear_1->next = temp;
temp->data = val;
temp->next = NULL;
rear_1 = temp;
}
}
void Display() {
temp = front_1;
if ((front_1 == NULL) && (rear_1 == NULL)) {
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are: ";
while (temp != NULL) {
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
void RevDisplay()
{
int a[100];
temp = front_1;
if ((front_1 == NULL) && (rear_1 == NULL)) {
cout<<"Queue Empty"<<endl;
return;
}
cout<<"The Reverse elements of Queue are: ";
int i=0;
while (temp != NULL) {
a[i]=temp->data;
temp = temp->next;
i++;
}
for(int k=i-1;k>=0;k--)
{
cout<<a[k]<<" ";
}
cout <<endl;
}
int main() {
int ch;
cout<<"1) Insert element in queue"<<endl;
cout<<"2) Reverse Display of elements of
queue"<<endl;
cout<<"3) Display of elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : "<<endl;
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: RevDisplay();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice of
selection"<<endl;
}
} while(ch!=4);
return 0;
}
Output:
I hope u like my effort.... thank u