What is Queue?
It is a linear structure that follows first in first out ( FIFO) in which the operations are performed.
Before implementation, there are two major fundamental operations performed on a queue.
- Enqueue: This operation is used to insert the element at the rear end of the queue. It returns nothing.
- Dequeue: This operation is used to delete the element from the front end. It also returns the element which has been removed from the front. It returns an integer value.
- Peek: This is the third operation performed by the queue. This returns the element which is pointed by the front pointer in the queue. But it does not delete the element from the queue.
- Queue underflow (isempty): It is used to check if the queue is empty or not.
#include <bits/stdc++.h>
using namespace std;
// Structure of Node.
struct Node
{
int data;
Node *link;
};
Node *front = 0;
Node *rear = 0;
//check if queue is empty or not
bool isempty()
{
if(front == NULL && rear == NULL)
return true;
else
return false;
}
//enter elements in queue
void enqueue( int value )
{
Node *ptr = new Node();
ptr->data= value;
ptr->link = NULL;
//If inserting the first element/node
if( front == NULL )
{
front = ptr;
rear = ptr;
}
else
{
rear ->link = ptr;
rear = ptr;
}
}
//delete/remove element from queue
void dequeue( )
{
if( isempty() )
cout<<"Queue is empty\n";
else{
//only one element/node in queue.
if( front == rear)
{
free(front);
front = rear = NULL;
}
else
{
Node *ptr = front;
front = front->link;
free(ptr);
}
}
}
//show the element at front
void peek( )
{
if( isempty())
cout<<"Queue is empty\n";
else
cout<<"element at front is:"<<front->data;
}
//to display queue
void display_queue()
{
if (isempty())
cout<<"Queue is empty\n";
else
{
Node *ptr = front;
while( ptr !=NULL)
{
cout<<ptr->data<<" ";
ptr= ptr->link;
}
}
}
//Main Function
int main()
{
int choice, flag=1, value;
while( flag )
{
cout << endl <<"1. Enter into queue" << endl << "2. Delete queue" << endl <<"3. Show Front" << endl << "4. Display queue" << endl << "5. Exit" << endl;
cin>>choice;
switch (choice)
{
case 1: cout<<"Enter Value:\n";
cin>>value;
enqueue(value);
break;
case 2: dequeue();
break;
case 3: peek();
break;
case 4: display_queue();
break;
case 5: flag = 0;
break;
}
}
return 0;
}
Microsoft Windows 10 is a widely used operating system in computers all over the world. If you have skills in Microsoft Windows 10 then you can get a Windows 10 Certification from StudySection which can help you in getting hired. A beginner level certification exam for newbies and an advanced level certification exam for experts is available on StudySection.