From ad81d0ef455434ea0eef219c96766b0b6987232c Mon Sep 17 00:00:00 2001 From: Paridhi Jain <83594113+Paridhicodes@users.noreply.github.com> Date: Tue, 12 Oct 2021 12:03:10 +0530 Subject: [PATCH] Add Circular Queue (#2528) --- DataStructures/Queues/CircularQueue.java | 115 +++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 DataStructures/Queues/CircularQueue.java diff --git a/DataStructures/Queues/CircularQueue.java b/DataStructures/Queues/CircularQueue.java new file mode 100644 index 00000000..5e9bbe08 --- /dev/null +++ b/DataStructures/Queues/CircularQueue.java @@ -0,0 +1,115 @@ +//This program implements the concept of CircularQueue in Java +//Link to the concept: (https://en.wikipedia.org/wiki/Circular_buffer) + +public class CircularQueue { + public static void main(String[] args) { + circularQueue cq= new circularQueue(5); + System.out.println(cq.isEmpty()); + System.out.println(cq.isFull()); + cq.enQueue(1); + cq.enQueue(2); + cq.enQueue(3); + cq.enQueue(4); + cq.enQueue(5); + + System.out.println(cq.deQueue()); + System.out.println(cq.deQueue()); + System.out.println(cq.deQueue()); + System.out.println(cq.deQueue()); + System.out.println(cq.deQueue()); + System.out.println(cq.isFull()); + System.out.println(cq.isEmpty()); + cq.enQueue(6); + cq.enQueue(7); + cq.enQueue(8); + System.out.println(cq.peek()); + System.out.println(cq.peek()); + cq.deleteQueue(); + + } +} +class circularQueue{ + int[] arr; + int topOfQueue; + int beginningOfQueue; + int size; + public circularQueue(int size){ + arr=new int[size]; + topOfQueue=-1; + beginningOfQueue=-1; + this.size=size; + } + public boolean isEmpty(){ + if(beginningOfQueue==-1){ + return true; + }else{ + return false; + } + } + + public boolean isFull(){ + if(topOfQueue+1==beginningOfQueue){ + return true; + }else if(topOfQueue==size-1 && beginningOfQueue==0){ + return true; + }else{ + return false; + } + } + + public void enQueue(int value){ + if(isFull()){ + System.out.println("The Queue is full!"); + } + else if(isEmpty()) { + beginningOfQueue=0; + topOfQueue++; + arr[topOfQueue]=value; + System.out.println(value+" has been successfully inserted!"); + }else{ + if(topOfQueue+1==size){ + topOfQueue=0; + }else{ + topOfQueue++; + } + arr[topOfQueue]=value; + System.out.println(value+" has been successfully inserted!"); + } + } + + public int deQueue(){ + if(isEmpty()){ + System.out.println("The Queue is Empty!"); + return -1; + }else{ + int res= arr[beginningOfQueue]; + arr[beginningOfQueue]=Integer.MIN_VALUE; + if(beginningOfQueue==topOfQueue){ + beginningOfQueue=topOfQueue=-1; + }else if(beginningOfQueue+1==size){ + beginningOfQueue=0; + }else{ + beginningOfQueue++; + } + return res; + } + + } + + public int peek(){ + if(isEmpty()){ + System.out.println("The Queue is Empty!"); + return -1; + }else{ + return arr[beginningOfQueue]; + } + } + + public void deleteQueue(){ + arr=null; + System.out.println("The Queue is deleted!"); + } + +} + +