Program to implement Queue using array

Concept: A queue data structure can be implemented using one dimensional array. But, queue implemented using array can store only fixed number of data values. The implementation of queue data structure using array is very simple, just define a one dimensional array of specific size and insert or delete the values into that array by using FIFO (First In First Out) principle with the help of variables ‘front’ and ‘rear’. Initially both ‘front’ and ‘rear’ are set to -1. Whenever, we want to insert a new value into the queue, increment ‘rear’ value by one and then insert at that position. Whenever we want to delete a value from the queue, then increment ‘front’ value by one and then display the value at ‘front’ position as deleted element

ALGORITHM:
1. Define a array which holds queue elements..
2. The operations on the queue are
     a)INSERT element into the queue
     b)DELETE element out of queue
3. INSERT element INTO queue
     a. Enter the element to be inserted into queue.
     b. If TOP is NULL
         i. The input data is the first node in queue.
         ii. The link of the node is NULL.
         iii. TOP points to that node.
     c. If TOP is NOT NULL
          i. The link of TOP points to the new node.
          ii. TOP points to that node.
4. DELETE element FROM queue
      a. If TOP is NULL
           i. the queue is empty
      b. If TOP is NOT NULL
           i. The link of TOP is the current TOP.
           ii. The pervious TOP is popped from queue.

5. The queue represented by linked list is traversed to display its content.

				
					#include<iostream.h> 
#include<conio.h> 
#include<stdlib.h> 
class queue 
{
int queue1[5]; 
int rear,front; 
public: queue() 
{ 
rear=-1; 
front=-1; 
}
void insert(int x) 
{
if(rear > 4) 
{
cout <<"queue over flow"; 
front=rear=-1; 
return; 
}
queue1[++rear]=x; 
cout <<"inserted" <<x;
}
void delet() 
{
if(front==rear) 
{
cout <<"queue under flow"; 
return; 
}
cout <<"deleted" <<queue1[++front]; 
} 
void display()
{
if(rear==front)
{ 
cout <<" queue empty"; 
return; 
}
for(int i=front+1;i<=rear;i++) 
cout <<queue1[i]<<" "; 
}
};
main() 
{
int ch; 
queue qu; 
cout <<"\n1.insert 2.delete 3.display 4.exit"; 
while(1) 
{ 
cout<<"\nEnter ur choice"; 
cin >> ch;
switch(ch) 
{
case 1: cout <<"enter the element"; 
cin >> ch; 
qu.insert(ch); 
break;
case 2: qu.delet(); 
break; 
case 3: qu.display(); 
break; 
case 4: exit(0); 
} 
}
return (0);
}
				
			

Leave a Reply