Programming Examples
Java Program to implement Queue using array
Write a JAVA Program to implement Queue using array
Solution
import java.util.*;
class Queue
{
int queue[]=new int[10];
int front=-1;
int rear=-1;
void insert(int num)
{
if(rear>=9)
{
System.out.println("Queue is Full");
}
else if(front==-1 && rear==-1)
{
front=0;
rear=0;
queue[rear]=num;
}
else
{
rear++;
queue[rear]=num;
}
}
void delete_data()
{
if(front==-1&&rear==-1)
{
System.out.println("Queue is Empty");
}
else if(front==rear)
{
System.out.println("deleted Element is "+queue[front]);
front=-1;
rear=-1;
}
else
{
System.out.println("Deleted Element is "+queue[front]);
front++;
}
}
public static void main(String arr[])
{
Queue obj=new Queue();
Scanner sc=new Scanner(System.in);
int ch,n;
do
{
System.out.println("1.Insert\n2.Delete\n0.Exit\nEnter any Choice :");
ch=sc.nextInt();
switch(ch)
{
case 1:
System.out.println("Enter the Data Item : ");
n=sc.nextInt();
obj.insert(n);
break;
case 2:
obj.delete_data();
break;
case 0:
System.exit(0);
break;
default:
System.out.println("Invalid Choice ");
}
}while(ch!=0);
}
}
Output
1.Insert
2.Delete
0.Exit
Enter any Choice :
1
Enter the Data Item :
10
1.Insert
2.Delete
0.Exit
Enter any Choice :
1
Enter the Data Item :
20
1.Insert
2.Delete
0.Exit
Enter any Choice :
1
Enter the Data Item :
30
1.Insert
2.Delete
0.Exit
Enter any Choice :
1
Enter the Data Item :
40
1.Insert
2.Delete
0.Exit
Enter any Choice :
2
Deleted Element is 10
1.Insert
2.Delete
0.Exit
Enter any Choice :
2
Deleted Element is 20
1.Insert
2.Delete
0.Exit
Enter any Choice :
2
Deleted Element is 30
1.Insert
2.Delete
0.Exit
Enter any Choice :
2
deleted Element is 40
1.Insert
2.Delete
0.Exit
Enter any Choice :
2
Queue is Empty
1.Insert
2.Delete
0.Exit
Enter any Choice :
0