Sunday 28 March 2021

Regular 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.qds;

import java.util.Scanner;

public class RegularQueue {

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

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.


public static void create(int data) {
if(rear==queue.length-1){
System.out.println("Queue is overflow !!!");
return;
}
if(front==-1 && rear==-1){
rear++;
front++;
}else{
rear++;
}
queue[rear]=data;

}

Below method is used to display element in queue.


public static void display() {
if((front==-1 && rear==-1) || front==rear+1){
System.out.println("Empty Queue");
return;
}
for(int i=front;i<=rear;i++){
System.out.println(queue[i]);
}

/*///OR
int j=front;
while(j<=rear){
System.out.println(queue[j++]);
}*/
}

Below Method is uses to delete the element from queue.


public static void delete() {

if((front==-1 && rear==-1) || front==rear+1){
System.out.println("Empty queue");
return;
}
System.out.println("Deleted element is "+queue[front++]);
}

}


No comments:

Post a Comment