circular queue using array
Fri May 24 2024 16:27:52 GMT+0000 (Coordinated Universal Time)
Saved by
@Farhana
public class p32_circularQ {
public static void main(String[] args) {
Queue q=new Queue(5);
q.add(0);
q.add(1);
q.add(2);
q.delete();
q.add(4);
while(!q.isEmpty()){
System.out.println(q.peek());
q.delete();
}
}
static class Queue {
static int arr[];
static int size;
static int rear;
static int front;
Queue(int n) {
arr = new int[n];
size = n;
rear = -1;
front=-1;
}
public static boolean isEmpty() {
return rear == -1 && front==-1;
// if(rear==-1){
// return true;
// }
// return false;
}
public static boolean isFull(){
return (rear+1)%size==front;
}
public static int delete() {
if (rear == -1) {
System.out.println("Empty");
return -1;
}
int temp = arr[0];
if(rear==front){
rear=front=-1;
}else{
front=(front+1)%size;
}
return temp;
}
public static void add(int data) {
if (isFull()) {
System.out.println("Queue is full");
return;
} //add 1st ele
if(front==-1){
front=0;
}
rear = (rear + 1)%size;
arr[rear] = data;
}
public static int peek() {
if (rear == -1) {
System.out.println("Empty");
return -1;
}
return arr[front];
}
}
}
content_copyCOPY
Comments