Sunday 28 March 2021

Circular Queue

Queue is first in first out (FIFO) data structure.we will implement queue data structure with one front and one rear end and one queue of array.
Initially front and rear end value will be [-1].
FRONT :- when we delete data from queue then front will increment.
REAR :- when we add element in queue then rear will increment.




package com.java.cqds;

import java.util.Scanner;

public class CircularQeue {
public static int[] queue=new int[5];
public static int front=-1,rear=-1;

public static void main(String[] args) {
System.out.println("Jai shree ram !!!");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("1. Create \t2. Display \t3. Delete");
int operation = sc.nextInt();
switch (operation) {

case 1:
System.out.println("Enter the queue value to create");
int data = sc.nextInt();
create(data);
break;
case 2:
display();
break;
case 3:
delete();
break;
default:
System.out.println("Operation not found !!!");
break;
}
}


}


Below method is used to create the queue.

private static void create(int data) {
if((front==0 && rear==queue.length-1)||(front==rear+1)){
System.out.println("Quee is full");
return;
}else{
if(front==-1 && rear==-1){
rear++;
front++;
}else{
rear++;
}
if(rear==queue.length){
rear=0;
}
queue[rear]=data;
}
}


Below method is used to display the queue.


private static void display() {
if(front==-1 && rear==-1){
System.out.println("Empty circular queue");
return;
}else{
int front1=front;
int rear1=rear;
if(front1>rear1){
while(front1<=queue.length-1){
System.out.println(queue[front1++]+" ");
}
front1=0;
while(front1<=rear1){
System.out.println(queue[front++]+" ");
}
}else{
while(front1<=rear1){
System.out.println(queue[front++]+" ");
}
}
}
}


Below method is used to delete the queue.


private static void delete() {
if(front==-1 && rear==-1){
System.out.println("Empty Circular linked list");
return;
}else{
System.out.println(queue[front]+"");
if(front==queue.length-1){
front=0;
}else{
front++;
}
if((front==rear+1)||(front==0 && rear==queue.length-1)){
rear=front=-1;
}
}
}



}

No comments:

Post a Comment