Queue implemented with SLL Code FIFO Queue using single liked list to hold a lis
ID: 3815929 • Letter: Q
Question
Queue implemented with SLL
Code FIFO Queue using single liked list to hold a list of integers. Use the C++ “struct” structure to create your queue items.
The user should be able to enter the values, once entered should be able to perform all the functions listed below
InitQueue – Initialize FIFO Queue
IsEmptyQueue – Checks for empty Queue
FrontQueue – Returns from item
BackQueue – Returns back item
PushQueue – Adds an item to end of Queue
PopQueue – Delete an item from of Queue
ClearQueue – Delete all items on the Queue
PrintQueue - Display all elements on the Queue
Explanation / Answer
Answer:
#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;
struct node *next;
}*p=NULL,*q=NULL,*front=NULL,*rear=NULL;
void InitQueue()
{
front=rear=NULL;
cout<<"Queue is Initialized ";
}
int IsEmptyQueue()
{
if(front==NULL)
return 0;
else
return 1;
}
int FrontQueue()
{
q=front;
if(q!=NULL)
{
cout<<"The First Element is:"<<q->data<<endl;
}
else
cout<<"Queue is empty ";
}
int BackQueue()
{
q=front;
if(q==NULL)
cout<<"Queue is Empty ";
else
{
while(q->next!=NULL)
{
q=q->next;
}
cout<<"The Last Element is "<<q->data<<endl;
}
}
void PushQueue(int x)
{
p=new node;
p->data=x;
p->next=NULL;
if(front==NULL)
{
front=rear=p;
rear->next=NULL;
}
else
{
rear->next=p;
rear=p;
rear->next=NULL;
}
}
int PopQueue()
{
int x;
if(front==NULL)
cout<<"Queue is empty ";
else
{
q=front;
x=q->data;
front=front->next;
delete(q);
return x;
}
}
void ClearQueue()
{
node *temp;
while(front!=NULL)
{
temp=front;
front=front->next;
free(temp);
}
front=rear=NULL;
}
void PrintQueue()
{
p=front;
if(front==NULL)
cout<<"No items to display ";
else
{
cout<<"The Queue elements are ";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
}
int main()
{
int choice,value,i;
cout<<"Displaying Menu ";
cout<<"1.Initialize Queue ";
cout<<"2.Check Queue empty ";
cout<<"3.Display First item ";
cout<<"4.Display Last item ";
cout<<"5.Push an item ";
cout<<"6.Pop an item ";
cout<<"7.Clear the Queue ";
cout<<"8.Print Queue elements ";
cout<<"0.exit ";
while(1)
{
cout<<"Enter your choice (1-8) and 0 to exit:";
cin>>choice;
switch(choice)
{
case 1:InitQueue();
break;
case 2:i=IsEmptyQueue();
if(i==0)
cout<<"Queue is Empty ";
else
cout<<"Queue is not Empty ";
break;
case 3:FrontQueue();
break;
case 4:BackQueue();
break;
case 5:cout<<"Enter an element to be pushed:";
cin>>value;
PushQueue(value);
break;
case 6:value=PopQueue();
cout<<"The deleted element is:"<<value<<endl;
break;
case 7:cout<<"Clearing Queue items.."<<endl;
ClearQueue();
break;
case 8:PrintQueue();
break;
case 0:exit(0);
default:cout<<"Invalid Choice";
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.