Circular Queue Code Example Java Programming



package yasolution.org;
import java.util.Scanner;

public class YaSolution {
   
    static int[] cQueue = new int[5];
    static int rear=0,front=0;
   
public static void main(String[] arg){
       
int cmd;
do{
cmd = get_cmd();
switch(cmd){
case 1:
insertFunc();
break;
case 2:
deleteFunc();
break;
case 3:
showFunc();
break;
default:
break;
}
}while(cmd!=4);
}

static int get_cmd(){
int n;
System.out.println("======Menu======");
System.out.println("1. Insert");
System.out.println("2. Delete");
System.out.println("3. Show");
System.out.println("4. Exit\n");
System.out.println("Choose option: ");
Scanner scan = new Scanner(System.in);
        n=scan.nextInt();
        System.out.println("");
return n;
}

static void insertFunc(){
if(front==(rear+1)%5){
System.out.print("Queue is full.\n");
}else{
System.out.print("Input data: ");
rear=(rear+1)%5;
                Scanner scan = new Scanner(System.in);
cQueue[rear]=scan.nextInt();
System.out.println();
}
}

static void deleteFunc(){
if(rear==front){
System.out.println("Queue is empty.\n");
}else{
System.out.println("Data deleted.\n");
front=(front+1)%5;
}
}
static void showFunc(){
if(rear==front)
System.out.print("Queue is empty.\n");
else{
int size=0;
System.out.print("Queue data are: ");
for(int i=front+1;i!=rear+1;i++){
i=i%5;
System.out.print(cQueue[i]+"    ");
size++;
}
System.out.print("\nQueue size is: "+size+"\n\n");
}
}      
}